Reputation: 10311
In my form if you click Submit twice quickly enough I get two successful form ajax posts. How can I stop duplicate posts?
From what I can tell
The form is sent twice, I create two items.
There are similarly named questions but they relate to disabling validation or disabling ajax. Ajax, jquery validation and server side validation (Post-Redirect-Get in MVC) are working just fine for me.
Just to be clear I'm using jQuery Mobile's Ajax navigation so I'm not writing any ajax.
Upvotes: 0
Views: 2863
Reputation: 10311
This is the solution I have now is:
$(document).on('submit', "form", null, function (e) {
$(this).find("input:submit")
.attr('disabled', 'disabled')
// the following is optional, arguably unnecessary
.delay(2000)
.queue(function (next) { $(this).removeAttr('disabled'); next(); });
});
(Updated to work in webkit)
The delay is just in case something goes wrong. In reality the form should get replaced and the replacement will not be disabled.
Better suggestions welcome.
Upvotes: 1
Reputation: 338406
$(document.body)
.on("input:submit", "click", function () {
var $this = $(this);
if ( !$this.is(".submitting") ) {
$this.addClass("submitting");
$.ajax({ url: "etc..."})
.done(function () {
// success callback;
})
.fail(function () {
// error callback;
})
.always(function () {
$this.removeClass("submitting");
})
}
});
This has the nice side effect that you can modify the style of the submit button with the submitting
CSS class. You could additionally/alternatively disable it and re-enable it in the always
callback.
Upvotes: 0