简体   繁体   中英

Form - Stopping Double Submit

All:

I am developing a web application using jquery/mvc/knockout that is taking data and posting it to the server in a fairly expensive transaction using $.post.

I don't want the user to "double click" or get impatient and click twice. Other then UI clues that something is happening, I have come up with a way that I believe works to achieve this purpose, but I want to make sure there are no caveats or hidden dangers to doing it this way.

Below is a JSFiddle that mimics a "submit via ajax" request using setTimeout. I set an internal field on the function "alreadyClicked" to true, run the "ajax request", and than set it back to false after post processing is finished. If you go to the below fiddle and have a debugger tool (a la firefox) that supports console.log you can go click crazy and watch as it enters the method and when it skips doing so.

http://jsfiddle.net/puhfista/vVUCm/7/

Thanks for any advice on this topic you feel like rendering.

Why don't you do like this:

$("<your element selector>").click(function(){
    $(this).attr('disabled', 'disabled');
    //  do your postback here
});

just don't forget to enable the element back once your postback completes

You can use this plugin to block the form submission when already in process.

http://www.malsup.com/jquery/block/

You mentioned in your question that you're using knockout in this project. The knockout way of achieving what you want would be to declare an observable in your view model called something like "isPosting":

self.isPosting = ko.observable(false);

In the html for your submit button, data bind to this observable:

<button data-bind="click:doPost, disable: isPosting">Submit</button>

In your "doPost" click handler, you need to set isPosting to true while the post is happening and false once it is complete.

@DimitryV: Thats not a great solution. You would be better keying of the submit event so that you catch things like the user pressing enter to submit the form.

$("form").submit(function () {
    $(this).attr('disabled', 'disabled');
    //  do your postback here
});

This way you would catch all submits. Just as a matter of note!

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