executing javascript after a form finishes submitting

33,041

Solution 1

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.

Solution 2

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.

Solution 3

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

Share:
33,041
Fallenreaper
Author by

Fallenreaper

Hacker, Programmer, software Dev, Software Engineer.. see my Twitter and website for more details.

Updated on September 20, 2020

Comments

  • Fallenreaper
    Fallenreaper over 3 years

    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(); });
    
    • Vikram
      Vikram over 11 years
    • Fallenreaper
      Fallenreaper over 11 years
      @thecodeparadox i didnt think that it would allow file and hidden elemement types to be sent to the server.
  • Niet the Dark Absol
    Niet the Dark Absol over 11 years
    Did you miss the whole thing about the form targetting a hidden iframe?
  • Eric J.
    Eric J. over 11 years
    No, I did not. That is a kludgy way to accomplish what is better done with Ajax.
  • Fallenreaper
    Fallenreaper over 11 years
    If i were to do it with ajax, how would i accomplish the different hidden or file type elements within the form?
  • Fallenreaper
    Fallenreaper over 11 years
    i use ajax for most other things, and like ajax, my goal was to on success, carry out the function. I just was not sure how to do it. If you can help me set up an ajax call which will send N hidden and N file elements to some url, that might work.
  • Fallenreaper
    Fallenreaper over 11 years
    it is an every expanding list of contents so i cant assume a specific numebr.
  • Fallenreaper
    Fallenreaper over 11 years
    @EricJ. I dont mean to spam. If this is possible. Can you show me an example of how to convert my form which contains 2 hidden elements and 2 file elements to a proper ajax request that would be great. I keep running into roadblocks when it comes to uploading files via ajax.
  • Eric J.
    Eric J. over 11 years
    Added an example. I have not used serialize() with file elements, but I assume it should work just fine.
  • Fallenreaper
    Fallenreaper over 11 years
    Thanks A lot Eric, If i can get it working, ill recoupe that downvote you got and give you the proper answer points. ;)
  • Fallenreaper
    Fallenreaper over 11 years
    @EricJ. I was trying to do as you said, and when you did serialize() it did not serialize the file element, only the hidden element. Confirmed that the form did contain the input type=file.
  • Fallenreaper
    Fallenreaper over 11 years
    in the main page, i tried to do $("frame#hider").ready(function(){...}); and that wasnt really working.
  • Fallenreaper
    Fallenreaper over 11 years
    @EricJ. I was looking at some thing, was thinking this might work. I am about to pass out, but i figured you might be able to give it a go? jquery.malsup.com/form seems to talk about malsup.github.com/jquery.form.js which wraps a form up and does some special magic then submits. I think it might work for files as well, but i need to confirm. Ill double check this link and write up some test cases tomorrow to see if they work.
  • Eric J.
    Eric J. over 11 years
    Looks like malsup should work, but there's another alternative too. Updated my answer.
  • Fallenreaper
    Fallenreaper over 11 years
    Im going to check and confirm. I was just confused because it was sending the path up. I was thinking it was going to send up a byte array. In that case, it doesnt do as requested. Request.Files has no byte array contents.
  • Fallenreaper
    Fallenreaper over 11 years
    i tried and that didnt work. I mean, i guess i could try the jquery equivalent too to see if that works. $().onload but what i did try was: document.frames["imageCollector"].onload = function () { top.document.frames['formDesignContents'].location = "WebFormDesigner.aspx?fm_id=" + top.SELECTED_FM_ID; };
  • Fallenreaper
    Fallenreaper over 11 years
    Looking at this, it does not work. It passes up the string of the source of the file, but not byte[] data.
  • Fallenreaper
    Fallenreaper over 11 years
    coworker took a look at it, and wrapped up your idea within a function.
  • mhdrad
    mhdrad over 9 years
    the guys who not use jQuery; use #5: frame.onload = null #8: frame.onload = callback;
  • MattCucco
    MattCucco over 6 years
    Hello Fallenreaper, I'm trying to implement this in a similar situation I have. Being fairly new to js, could you explain how someone would implement this? I am trying to get my code to wait for the form to submit, then redirect the user to a new page. EDIT: Here is actually a question i put up for this issue: stackoverflow.com/questions/48269685/…
  • Fallenreaper
    Fallenreaper over 6 years
    In my example here, the form will change the frame's location, so when the form submits, it would change the frame instead of the host page. Then you can see there is a bound onload for the frame which will execute the SuccessFunction you defined.
  • MattCucco
    MattCucco over 6 years
    So just to clarify (apologies I am still learning the in's and out's of web dev), I would need to attach this function to the 'save' button and define a success function (which could actually be my PreSave Function i believe). Am i following correctly? Also what would I need to provide for the other parameters as well? Perhaps you could point me to a good article on this stuff ( I have never touched these things before). Again thank you for your help!
  • Fallenreaper
    Fallenreaper over 6 years
    This function takes 3 parameters, form that you are submitting, a frame on the page, and your success call back. In your code, you would call this function. This use case is attached to anything clickable not related to the form itself. An anchor tag for example. The form and frame are jQuery objects in this case. This isnt a pre-submit function, the success function would be what happens AFTER the call is successful.