I am trying to upload a text file to a python script. If I just upload form data and use
form_contents = $(this).serialize() + "&async=true";
then the form will stay on the web page and display the results. If I use
var formData = new FormData($('form')[0]);
it submits the form and data file but it doesn't stay on the web page. How do I add + &async=true
to get it to stay on the web page. Or is there a different way to do this?
Stays on web page but doesn't upload file:
$('#upload').submit(function () { form_contents = $(this).serialize() + "&async=true"; form_action = $(this).attr('action'); $.ajax({ type: 'post', data: formData, url: form_action, success: function (result) { $('#upload').html(result); } }); return false; });
Doesn't stay on web page but uploads file:
$('#upload').submit(function () {
var formData = new FormData($('form')[0]);
form_action = $(this).attr('action');
$.ajax({
type: 'post',
xhr: function() {
myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
myXhr.upload.addEventListener('progress',progressHandlingFunction, false);
}
return myXhr;
},
data: formData,
url: form_action,
success: function (result) {
$('#upload').html(result);
}
});
return false;
});
Thanks for your help,
Matt
You need to also set the contentType and processData parameters to false.
$('#upload').submit(function () {
var formData = new FormData($('form')[0]);
form_action = $(this).attr('action');
$.ajax({
type: 'post',
xhr: function () {
myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
myXhr.upload.addEventListener('progress', progressHandlingFunction, false);
}
return myXhr;
},
data: formData,
url: form_action,
processData: false,
contentType: false,
success: function (result) {
$('#upload').html(result);
}
});
return false;
});
however, if an error occurs, the form will continue to submit because it never reaches return false;
. to stop that so you can see the error, use event.preventDefault.
$('#upload').submit(function (e) {
e.preventDefault();
var formData = new FormData($('form')[0]);
form_action = $(this).attr('action');
$.ajax({
type: 'post',
xhr: function () {
myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
myXhr.upload.addEventListener('progress', progressHandlingFunction, false);
}
return myXhr;
},
data: formData,
url: form_action,
processData: false,
contentType: false,
success: function (result) {
$('#upload').html(result);
}
});
});
wouldn't you just simply add a hidden input element to the form?<input type=hidden name="async" value="true">
...then this value would automatically be a part of your serialized data in formData