How to upload file using jquery and ajax? - javascript

I am trying to upload a file alone with other form data using AJAX. Here I am following this bootstrap and jquery plugin.
I can figure it out without file uploading, But I want to upload a file with my form.
This is how I tried it:
.on('success.form.fv', function(e) {
// Save the form data via an Ajax request
e.preventDefault();
var $form = $(e.target),
formData = new FormData(),
params = $form.serializeArray(),
files = $form.find('[name="new_product_image"]')[0].files,
id = $form.find('[name="product_id"]').val();
// The url and method might be different in your application
$.ajax({
url: './includes/process_edit_products.php',
method: 'POST',
//data: $form.serialize()
data: formData,
cache: false,
contentType: false,
processData: false,
}).success(function(response) {
response = jQuery.parseJSON(response);
// Get the cells
var $button = $('button[data-id="' + response.product_id + '"]'),
$tr = $button.closest('tr'),
$cells = $tr.find('td');
// Update the cell data
$cells
.eq(0).html(response.product_name).end()
.eq(1).html(response.price).end()
.eq(2).html(response.product_des).end();
// Hide the dialog
$form.parents('.bootbox').modal('hide');
// You can inform the user that the data is updated successfully
// by highlighting the row or showing a message box
bootbox.alert('The product is updated successfully.');
});
});
UPDATE: This is my HTML:
<form id="userForm" method="post" class="form-horizontal" enctype="multipart/form-data" style="display: none;">
<div class="form-group">
<label class="control-label" style="width:32%;">ID</label>
<div class="col-xs-3">
<input type="text" class="form-control" name="product_id" readonly />
</div>
</div>
<div class="form-group">
<label class="control-label" style="width:32%;">Product Name:</label>
<div class="col-xs-5">
<input type="text" class="form-control" name="product_name" />
</div>
</div>
<div class="form-group">
<label class="control-label" style="width:32%;">Product Price</label>
<div class="col-xs-5">
<input type="text" class="form-control" name="product_price" />
</div>
</div>
<div class="form-group">
<label class="control-label" style="width:32%;">Product Description</label>
<div class="col-xs-5">
<input type="text" class="form-control" name="product_des" />
</div>
</div>
<div class="form-group">
<label class="control-label" style="width:32%;">New Product Image:</label>
<div class="col-xs-5">
<input type="file" size="32" name="new_product_image">
<p class="help-block">*Only for jpg, gif and PNG files.</p>
</div>
</div>
<div class="form-group">
<div class="col-xs-5 col-xs-offset-4">
<button type="submit" class="btn btn-primary">Update Product</button>
</div>
</div>
</form>
Can anybody tell me where I have gone wrong. Any help would be greatly appreciating.
Thank you.

I think your formData is empty. Try to put these lines before send:
$.each(files, function(i, file) {
// Prefix the name of uploaded files with "uploadedFiles-"
// Of course, you can change it to any string
formData.append('uploadedFiles-' + i, file);
});
$.each(params, function(i, val) {
formData.append(val.name, val.value);
});
Like they did here http://formvalidation.io/examples/ajax-submit/#using-ajax-to-submit-form-data-including-files

Related

How to submit form including image on button click [duplicate]

This question already has answers here:
Sending formdata for file upload using ajax
(3 answers)
Closed 9 months ago.
I have this HTML:
<form id="form" enctype="multipart/form-data">
<div class="row">
<div class="col">
<div class="mb-3">
<label for="design_title" class="form-label">Ttile of the design</label>
<input type="text" name="design" class="form-control" id="design_title">
</div>
</div>
<div class="col">
<div class="mb-3">
<label for="design" class="form-label">Upload a new design</label>
<input type="file" name="design" class="form-control" id="design">
</div>
</div>
</div>
<div class="mb-3">
<div class="row">
<div class="col">
<label for="fontsize" class="form-label">Enter the font size</label>
<input type="number" name="design_font_size" class="form-control" id="fontsize">
</div>
<div class="col">
<label for="position_x" class="form-label">Position X</label>
<input type="number" name="design_x" class="form-control" id="position_x">
</div>
<div class="col">
<label for="position_y" class="form-label">Position Y</label>
<input type="number" name="design_y" class="form-control" id="position_y">
</div>
</div>
</div>
<div class="mb-3">
<label class="form-label" for="domain">Choose a domain</label>
<select name="domain" id="domain" class="form-control" data-form="design_output">
<option value="">--Choose--</option>
<?php
$get_domain = mysqli_query( $mysqli, "SELECT * FROM eg_domains");
if( mysqli_num_rows( $get_domain ) > 0 ) {
while( $get_result = mysqli_fetch_array( $get_domain, MYSQLI_ASSOC ) ) {
$domain_name = $get_result['domain_name'];
$company = $get_result['company_name'];
$domain_id = $get_result['domain_id'];
echo "<option value='$domain_id'>$domain_name ($company)</option>";
}
}
?>
</select>
</div>
<button type="button" class="btn btn-primary ajax-btn output-desing" data-form="output_design">Output Design</button>
<button type="submit" class="btn btn-success ajax-btn">Save Design</button>
<div class="mt-3">
<div class="result"></div>
</div>
</form>
Now, on Output Design button click I want to get all the data including image.
So, I am doing this in JQuery/Ajax:
$(document).on("click", ".output-desing", function (e) {
e.preventDefault();
var form = document.querySelector(".output-desing");
var form_name = form.dataset.form;
var data = $("#form").serialize() + "&form=" + form_name;
// var data = '1';
console.log(data);
$.ajax({
dataType: "html",
type: "GET",
url: 'helper/process.php',
data: data,
contentType: false,
cache: false,
processData: false,
beforeSend: function () {
$(".output-design").val("Please wait...");
},
success: function (data) {
$(".output-design").html(data);
}
});
});
But I can get only form data not image data.
How can I get all the data including image data on that button click?
Anyways, I fix it this way:
var form = document.querySelector(".output-desing");
var form_name = form.dataset.form;
var data = new FormData(document.getElementById("form"));
data.append('form', form_name);

AJAX form submission - Each click submits the form i++ number of times

I have an issue where my form submission in with AJAX works fine the first time, but if I click the submit button again, or press enter, the form submits twice. A third click causes the form to be submitted 3 times and so on. I've tried inserting return false and preventDefault() within the scripts.js file to no avail.
An implementation of my form can be found here and the resulting list of output can be found here
Additionally, I notice that the scripts.js never proceeds to the line with document.getElementById('test').innerHTML="this works3";
Any help would be greatly appreciated. Thank you!
index.html
<form id="form1" action="addpost.php" method="post">
<div class="form-group" >
<label for="title">Title:</label>
<input name="title" type="title" class="form-control " id="title" placeholder="Enter title (Compulsory)" required>
<span class="help-block">This is some help text that breaks onto a new line and may extend more than one line.</span>
</div>
<div class="form-group">
<label for="name">Name:</label>
<input type="name" class="form-control" id="name">
<span class="help-block">This is some help text that breaks onto a new line and may extend more than one line.</span>
</div>
<div class="form-group">
<label for="article">Article:</label>
<textarea name="article" class="form-control" rows="5" id="article"></textarea>
</div>
<div class="form-group">
<label for="img1">Image 1:</label>
<input type="file" class="form-control" id="img1" accept="image/*">
<span class="help-block">This is some help text that breaks onto a new line and may extend more than one line.</span>
</div>
<label id="test">hi</label>
<button class="btn btn-primary" onclick="poop()">Button</button>
<input type="submit" class="btn btn-primary" onclick="poop()" value = "submit"/>
</form>
scripts.js
function poop()
{
document.getElementById('test').innerHTML="this works";
var form = $('#form1');
document.getElementById('test').innerHTML="this works2";
form.submit(function (event)
{
$.ajax
({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
success: function (data)
{
alert('ok');
}
});
});
document.getElementById('test').innerHTML="this works3";
}
Thanks to Liam and Vinod for pointing me in the right direction. I included the script to override the submit function in the index.html file. Solved the problem quite nicely.
index.html
<form id="form1" action="addpost.php" method="post">
<div class="form-group" >
<label for="title">Title:</label>
<input name="title" type="title" class="form-control " id="title" placeholder="Enter title (Compulsory)" required>
<span class="help-block">This is some help text that breaks onto a new line and may extend more than one line.</span>
</div>
<div class="form-group">
<label for="name">Name:</label>
<input type="name" class="form-control" id="name">
<span class="help-block">This is some help text that breaks onto a new line and may extend more than one line.</span>
</div>
<div class="form-group">
<label for="article">Article:</label>
<textarea name="article" class="form-control" rows="5" id="article"></textarea>
</div>
<div class="form-group">
<label for="img1">Image 1:</label>
<input type="file" class="form-control" id="img1" accept="image/*">
<span class="help-block">This is some help text that breaks onto a new line and may extend more than one line.</span>
</div>
<label id="test">hi</label>
<input type="submit" class="btn btn-primary" value = "submit"/>
</form>
// script included within body of html
<script type="text/javascript">
var form = $('#form1');
document.getElementById('test').innerHTML="this works2";
form.submit(function (event)
{
event.preventDefault();
$.ajax
({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
success: function (data)
{
alert('ok');
}
});
});
</script>

submit function submits twice after first submisson jquery, PHP

function slideupSubmit (name) {
$(name).submit(function ( event ) {
event.preventDefault();
var target = $(this).attr("action");
var response = $(this).attr("response");
var formName = $(this).attr("id");
$.post(target,
$(this).serialize() + '&' + $.param({ 'formName':formName, response : response}),
function (data) {
$(response).html(data);
$(name).hide();
$(name)[0].reset();
}
);
});
};
function resetForm (name){
$(name).show();
};
Im really new at this and only been coding for a few months so if my code is really bad I apologize, and if the solution is very easy, please forgive me.
I wrote this code so I could reuse it to submit diffrent forms on my page and have a response sent to a div above it. Im able to post everything I want but after the first time it posts, if I post again, it will post twice. Then three times. I know I did something wrong but I cant find the error.
I include this on my response to allow the form to be brought back after hiding.
<a onClick="resetForm('.$_POST['formName'].')" href="#" response=""> New Form?</a>
Here is the form.
<!-- Form 1 --->
<div class="row ">
<div class="col-xs-12">
<div class="well well-dark ">
<h4>Update Contacts</h4>
<span class="contactUpdate-response text-success"></span>
<form id="contactUpdate" class="form form-inline hidden contact-form" response=".contactUpdate-response" method="post" action="ajax/contactUpdate.php">
<div class="form-group">
<input hidden name="contact_entry" value="1"/>
</div>
<div class="form-group">
<label>Contact Title:</label>
<input class="form-control" name="contact_title" required />
</div>
<div class="form-group">
<label>Link to Employee</label>
<select name="empId" class="form-control select-emp-name"></select>
</div>
<div class="form-group">
<label>Category:</label>
<select name="category"class="form-control select-contact-categories ">
</div>
<div class="form-group">
<label>Link to Location</label>
<select name="locat_id" class="form-control select-location"></select>
</div>
<div class="form-group">
<label>Number:</label>
<select name="extId" class="form-control select-dig-ext"></select>
</div>
<div class="form-group">
<input hidden name="updateBy" value="24"/>
</div>
<div class="form-group">
<input onclick="slideupSubmit(contactUpdate)" type="submit" class="form-control btn btn-primary" value="Update List" />
</div>
</form>
</div>
</div>
</div>
<!--- -->
<input type="submit" class="form-control btn btn-primary" value="Update List" />
take your event listener out of function
and remove onclick=...
$(name).submit(function ( event ) {
event.preventDefault();
var target = $(this).attr("action");
var response = $(this).attr("response");
var formName = $(this).attr("id");
$.post( target, $(this).serialize()
+'&'+$.param({ 'formName': formName,
response : response}),
function(data){$(response).html(data);
$(name).hide();
$(name)[0].reset();
});

PHP contact form with post function not working

This is my javascirpt code
var form = $('#main-contact-form');
form.submit(function(event){
event.preventDefault();
var form_status = $('<div class="form_status"></div>');
$.ajax({
url: $(this).attr('action'),
beforeSend: function(){
form.prepend( form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>').fadeIn() );
}
}).done(function(data){
form_status.html('<p class="text-success">Thank you for contact us. As early as possible we will contact you</p>').delay(6000).fadeOut();
});
});
I am not getting the field values post function is unable to fetch it
<div class="contact-form wow fadeIn" data-wow-duration="1000ms" data-wow-delay="600ms">
<div class="row">
<div class="col-sm-6">
<form id="main-contact-form" name="contact-form" method="post" action="sendemail.php">
<div class="row wow fadeInUp" data-wow-duration="1000ms" data-wow-delay="300ms">
<div class="col-sm-6">
<div class="form-group">
<input type="text" id="name" name="name" class="form-control" placeholder="Name" required="required">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<input type="email" id="email" name="email" class="form-control" placeholder="Email Address" required="required">
</div>
</div>
</div>
<div class="form-group">
<input type="text" id="subject" name="subject" class="form-control" placeholder="Subject" required="required">
</div>
<div class="form-group">
<textarea name="message" id="message" class="form-control" rows="4" placeholder="Enter your message" required="required"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn-submit">Send Now</button>
</div>
</form>
</div>
This is my html code
It seems like you're just sending an empty ajax request.
You will need a method and the form data to send, for example:
$.ajax({
url: $(this).attr('action'),
type: 'post',
dataType: 'json', // <-- not sure if about this
data: form.serialize(),
beforeSend: function(){
...
Also see Submit a form using jQuery
Try setting the method to be "POST" and data in $.ajax, like this:
$.ajax({
method: "POST",
data: form.serialize(),
etc...
Also, it would help to see your PHP file.

Ajax call is not working?

Hi i am trying to submit a form in bootstrap modal. This modal is going to open based on a href click event. This a href tag is going to b generated dynamically in ajax call using Jquery.
format of the a href tag is below to call bootstrap modal.
'<a id="addvideo" data-toggle="modal" data-title="'+field.title+'" data-id="'+field.video_id+'" data-desc="'+field.description+'" data-channelname="'+field.channel_name+'" data-yudate="'+field.created_date+'" href="#form-content">'+field.title+'</a>'
The modal which i am calling is below shown.
<div id="form-content" class="modal hide fade in" style="display: none;">
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h3>Add Video</h3>
</div>
<div class="modal-body">
<form name="addvideo" class="form-horizontal" action="#" id="addchannelvideo">
<div class="control-group">
<label class="control-label" for="videotitle">Title</label>
<div class="controls">
<input type="text" id="videotitle" name="videotitle">
</div>
</div>
<div class="control-group">
<label class="control-label" for="videoid">Video ID</label>
<div class="controls">
<input type="text" id="videoid" name="videoid">
</div>
</div>
<div class="control-group">
<label class="control-label" for="videodesc">Description</label>
<div class="controls">
<textarea id="videodesc" name="videodesc"></textarea>
</div>
</div>
<div class="control-group">
<label class="control-label" for="channelname">Channel</label>
<div class="controls">
<input type="text" id="channelname" name="channelname">
</div>
</div>
<div class="control-group">
<label class="control-label" for="actors">Actors</label>
<div class="controls">
<input type="text" id="actors" name="actors">
</div>
</div>
<div class="control-group">
<label class="control-label" for="directors">Directors</label>
<div class="controls">
<input type="text" id="directors" name="directors">
</div>
</div>
<div class="control-group">
<label class="control-label" for="producers">Producers</label>
<div class="controls">
<input type="text" id="producers" name="producers">
</div>
</div>
<div class="control-group">
<label class="control-label" for="musicians">Music Directors</label>
<div class="controls">
<input type="text" id="musicians" name="musicians">
</div>
</div>
<div class="control-group">
<label class="control-label" for="cast">Cast</label>
<div class="controls">
<input type="text" id="cast" name="cast">
</div>
</div>
<div class="control-group">
<label class="control-label" for="yudate">Youtube Uploaded Date</label>
<div class="controls">
<input type="text" id="yudate" name="yudate">
</div>
</div>
<div class="control-group">
<label class="control-label" for="cudate">CMS Uploaded Date</label>
<div class="controls">
<input type="text" id="cudate" name="cudate">
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" id="orderno">Priority video
</label>
<label class="checkbox">
<input type="checkbox" id="hidevideo">Hide in Mobile App
</label>
<button class="btn btn-success" id="submit"><i class="icon-white icon-ok"></i> Submit</button>
<button class="btn btn-inverse"><i class="icon-white icon-circle-arrow-left"></i> Cancel</button>
</div>
</div>
</form>
</div>
</div>
Now to call modal based on click i am using below javascript code and in this code only i am passing data to modal by setting text boxes values in modal using Jquery like below.
$(document).on("click", "#addvideo", function () {
var videoid = $(this).data('id');
var videotitle = $(this).data('title');
var videodesc = $(this).data('desc');
var channelname = $(this).data('channelname');
var yudate = $(this).data('yudate');
$(".modal-body #videoid").val( videoid );
$(".modal-body #videotitle").val( videotitle );
$(".modal-body #videodesc").val( videodesc );
$(".modal-body #channelname").val( channelname );
$(".modal-body #yudate").val( yudate );
});
Ajax call function is below one.
$(document).ready(function(e) {
$('input#submit').click(function() {
var title = $('#videotitle').val();
var videoid = $('#videoid').val();
var description = $('#videodesc').val();
var channel = $('#channelname').val();
var actors = $('#actors').val();
var directors = $('#directors').val();
var producers = $('#producers').val();
var musicians = $('#musicians').val();
var cast = $('#cast').val();
var yudate = $('#yudate').val();
var orderno = 0;
if($("#orderno").is(':checked'))
{
var orderno = 1;
}
var hidevideo = 0;
if($("#hidevideo").is(':checked'))
{
var hidevideo = 1;
}
var postdata = "title="+title+"&videoid="+videoid+"&description="+description+"&channel="+channel+"&actors="+actors+"&directors="+directors+"&producers="+producers+"&musicians="+musicians+"&cast="+cast+"&orderno="+orderno+"&hidevideo="+hidevideo+"&yudate="+yudate;
$.ajax({
type: 'POST',
url: 'addvideo.php',
data: "title="+title+"&videoid="+videoid+"&description="+description+"&channel="+channel+"&actors="+actors+"&directors="+directors+"&producers="+producers+"&musicians="+musicians+"&cast="+cast+"&orderno="+orderno+"&hidevideo="+hidevideo+"&yudate="+yudate,
datatype:'json',
success: function(response) {
$("#form-content").modal('hide');
alert(response);
},error: function(){
alert("video categorization failed");
}
});
});
});
Now my modal is loading fine and values are showing up in assigned text boxes once the modal loaded on click on href tag. But after click on submit it is redirecting to the same php url and all the parameters are adding as query parameters and weird thing is if i open modal second time and try to submit ajax call is working.
$('input#submit').click(function(e) {
e.preventDefault();//
.....rest of the code here
});
if the form elements are loaded dynamically then try delegating click
$(document).on("click", "#submit", function (e) {
e.preventDefault();
});
try using following tested and workinf code for AJAX call
// Get the form data. This serializes the entire form. pritty easy huh!
var form = new FormData($('#form_step4')[0]);
$.ajax({
type: "POST",
url: "savedata.php",
data: form,
cache: false,
contentType: false,
processData: false,
success: function(data){
//alert("---"+data);
alert("Settings has been updated successfully.");
window.location.reload(true);
}
});
You need to load jQuery for this.

Categories