A snippet code to show you how to avoid double postback with jQuery. This is useful for "Create" situations and the user clicks twice (or more) on the submit button.

This snippet code allows you to block a double submit from the user. In this case, the normal behavior if no unique constraint check is done is that the record is created twice (or the number of times the user clicked on) on the database.

In my case, I have a contacts table. Creating a unique index on "First Name" + "Last Name" can block certain real situations (i.e. 2 employees have the same "First Name" + "Last Name"), so my solution is to disable the submission until the record is created. When the record takes some time to reply, the user tends to click again, submitting twice.

This code handles situations when you are using jQuery and jQuery.Validate

$("form").submit(function () {
    $(":submit", this).attr("disabled", "disabled");
    if (!$(this).valid()) {
        // If not client-side valid, then re-enable button to a future validation
        $(":submit", this).removeAttr("disabled");
        return false;
    }
    return true;
});

The cool thing is you can reuse it for all the pages of your application, because it is generic enough to be in a Javascript file loaded in a master page.

Discussion

Stephane Erard
Stephane Erard
09 mai, 2011 09:11

Hey !

One step forward (I guess) :

When sending the form (using .ajaxForm() plugin), what I usually do, as I use the BlockUI plugin, is to .block() $(this) :) So user can see there is an interaction (xhr) and wait for it to complete.

Thanks ;)

19 juil., 2011 06:44

Interesting comment Stephane. The only drawback is you must ensure the classical POST and the Ajax POST end at the same location (Controller method). Some MVC frameworks distinguish both.

FroG
FroG
08 déc., 2011 08:22

Hello, your approach can be extended outside JQuery, even not using any UI framework, using the "standard" disable attribute of the button: you start any action by disabling the button so that the user cannot click again, you perform all the Ajax calls you want, and at the end you enable again the button (if needed).

I think that's a good practice that should be shared to prevent the applications from click-maniacs.

13 déc., 2011 05:27

In fact I used it, because I add these multiple adds on my app.

No new comments are allowed on this post.