0

I have a function that starts on the submission of a form #uploadform which is enctype="multipart/form-data". The issue is that when this form is submitted, I run another function that sends a post request to a document and receives information. I would like this information to submit with the initial form #uploadform but it seems that this post call happens after the form submission so the values do not get added. #progress_key is added to the form successfully because it happens before the post call. Anyone have any ideas around this?

$('#uploadform').submit(function(){

beginUpload();

}


function beginUpload() {
$('#progress_key').val(rand_id);

$.ajax({
type: "POST",
url: "progressbar/initial.php",
data: 'data,
dataType: 'json',
success: function(response, statusText) {

if(response.error == '') {  

vid_id=response.vid_id;
file_name=response.file_name;

$('#file_name').val(vid_id);
$('#vid_id').val(file_name);
}
}
});
}
Scarface
  • 3,845
  • 7
  • 41
  • 71

1 Answers1

3

To do this, and avoid making a sychronous ajax request you can return false from your submit handler like this:

$('#uploadform').submit(function(){
    beginUpload();
    $(this).unbind('submit');
    return false;
}

Then submit it at the end of the success function of your ajax call like this:

$('#uploadform').submit();
Paul
  • 139,544
  • 27
  • 275
  • 264
  • You would have to call the form element's `submit()` method, not the jQuery one as this will just invoke the handler again. Ie, `document.getElementById('uploadform').submit()` – Phil Sep 01 '11 at 04:51
  • @Phil jQuery docs say this form of submit calls .trigger instead of .bind, so it's the same as calling the form's submit method – LeleDumbo Sep 01 '11 at 04:54
  • @Phil It is. `submit()` is the short form of `trigger('submit')`. Note the differences between `trigger()` and `triggerHandler()`. `trigger()` will attempt to cause the default browser action for that event as well, in this case submitting the form. – Paul Sep 01 '11 at 05:01
  • @Phil See this for more: http://stackoverflow.com/questions/3772537/triggerhandler-vs-trigger-in-jquery – Paul Sep 01 '11 at 05:01
  • 1
    @Phil Hmm... It seems that jQuery considers the default browser action to be calling the onsubmit event handler to decide whether to submit it or not. Thanks for pointing it out and proving it, haha. Sorry for doubting :P I edited my post. – Paul Sep 01 '11 at 05:08
  • You can also set an attribute in the ajax call async: false this will make the script wait for a response (overriding "Asynchronous" but who's counting) – Wrenbjor Sep 01 '11 at 05:58