executing javascript after a form finishes submitting


I am trying to submit some files to my database with a form. The form has a target of a hidden iframe. When it finishes loading, i was wanting to show a message.

 $("form#formPost").submit();
 customFunction();

This example seems to not finish submitting before firing off customFunction(), which is very bad for what i was designing.

Is there a way to do something which will fire when it completes sending the data? I was looking around on stackoverflow, and there arent many posts directly about this. I feel that i would have to go into the target iframe and execute the code in there when it is ready, etc. Is there a way to make it do as i want?

options i have tried:

 $("form#formPost").submit(function(){ customFunction(); });

Coworker Created a function which does just this.

function SubmitWithCallback(form, frame, successFunction) {
   var callback = function () {
       if(successFunction)
           successFunction();
       frame.unbind('load', callback);
   };

   frame.bind('load', callback);
   form.submit();
}

This function takes the form you are submitting, the forms target iframe, and an anon function which will be executed on success.


If you submit the form in the traditional manner, you are essentially saying "I am done with this page. Here's a bunch of form data for you, web server, to render my next page". The web server takes the form data and returns to the browser the next page.

If you do not wish a page reload, you can submit your form using Ajax. That is quite straightforward with jQuery:

http://api.jquery.com/jQuery.ajax/

Using Ajax, you have well-defined events when the submission completes, when it is successful, and when it errors.

I would not recommend the approach of targeting a hidden iframe. Ajax is better suited for this type of processing.

UPDATE

Here's an example of how you might structure the Ajax

<form id='myFormId'>
<!-- Form fields, hidden, file or otherwise -->
</form>

var formVars = $("#myFormId").serialize();
$.ajax({ url: ajaxUrl, cache: false, type: 'POST', data: formVars, 
    success: function (data) { handleSuccessCase }, 
    error: handleAjaxError });

UPDATE 2

Based the comments in https://stackoverflow.com/a/5513570/141172

You can try:

var formVars = $('#myFormId').serialize() + '&foo=' + $('#id_of_your_file_input').val()

Alternatively, you can try the plugin you suggest in your comments, which is the same solution as in the linked answer above.


Perhaps the easiest thing to do is attach an onload event on the iframe. When the form has finished submitting, the event will fire.