Prevent double form submission in jQuery

2019-03-28 08:46发布

问题:

I have a form that users use to input information about a posting. When complete they click 'Save' to update. However, in some rare cases (10 in 15,000 records) the user has double clicked the save button and caused a double form submission duplicating items for the posting.

I tried using this to prevent it:

$('input[type=submit]').click(function(){
    $('input[type=submit]').attr('disabled',true);
    //return true;
});

But the problem with this, it works perfectly in Safari / Firefox etc, but does not work in Internet Explorer 8 (and probably not for 6 & 7)

When I press save in IE8, the button is disabled and that's it, no form submission at all.

(I tried it with and without return true;)

回答1:

I'm not sure so this is a complete guess, but it maybe up to your selector there. Try instead:

$('input:submit').click(function() {
    $(this).attr('disabled', true);
});#

You may also try to intercept the submit event itself:

$('form').bind('submit', function(e) {
     $(this).find('input:submit').attr('disabled', 'disabled');
});


回答2:

You need to handle the onsubmit event of the form rather than the click event of the submit button.



回答3:

User can press enter to submit form too, so instead of binding button click event , use the form submit. Also instead of disabling, hide the submit button by replacing it with some loading image.

jQuery("form").submit(function () {
        jQuery(":submit", this).css("display", "none");
        jQuery(":submit", this).after("<span><img src='loading.gif' /></span>");
});


回答4:

Chirs, this is a very common problem that every web developer faces. And guess what, it has a very well accepted solution.

The solution is known as PRG (Post -> Redirect -> Get). Read more about this on http://en.wikipedia.org/wiki/Post/Redirect/Get

Basically you need to leave the page in an HTTP GET mode so that even if user refreshes the page, no data should get re-submitted. So, you submit the form, redirect the page to a URL which displays the recently submitted data by doing a GET request.

EDIT As per the comment below seems like Chris is already following the above paradigm. Great. But he is still seeing duplicate form submissions. I would suggest on the first submission, replace the button with a loading image (as the first thing) so that the user does not see any button to re-click :)

$(document).ready(function() {
   // function which handles form submission
   $(#submitButton).replaceWith("<img src="./images/myLoader.gif>");
   // do the actual form submission after this
   ...
});