简体   繁体   中英

Prevent double form submission in jQuery

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;)

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');
});

您需要处理表单的onsubmit事件而不是提交按钮的click事件。

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>");
});

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
   ...
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM