Prevent double form submission in jQuery

2019-03-28 08:44发布

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

4条回答
别忘想泡老子
2楼-- · 2019-03-28 09:11

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>");
});
查看更多
可以哭但决不认输i
3楼-- · 2019-03-28 09:23

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

查看更多
虎瘦雄心在
4楼-- · 2019-03-28 09:29

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');
});
查看更多
放荡不羁爱自由
5楼-- · 2019-03-28 09:33

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
   ...
});
查看更多
登录 后发表回答