executing javascript after a form finishes submitting

后端 未结 3 1070
慢半拍i
慢半拍i 2020-12-19 08:38

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.



        
相关标签:
3条回答
  • 2020-12-19 09:06

    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.

    0 讨论(0)
  • 2020-12-19 09:09

    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.

    0 讨论(0)
  • 2020-12-19 09:10

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

    0 讨论(0)
提交回复
热议问题