Prevent Double Submission of Forms in Jquery

Prevent double submission of forms in jQuery

Update in 2018: I just got some points for this old answer, and just wanted to add that the best solution would be to make the operation idempotent so that duplicate submissions are harmless.

Eg, if the form creates an order, put a unique ID in the form. The first time the server sees an order creation request with that id, it should create it and respond "success". Subsequent submissions should also respond "success" (in case the client didn't get the first response) but shouldn't change anything.

Duplicates should be detected via a uniqueness check in the database to prevent race conditions.


I think that your problem is this line:

$('input').attr('disabled','disabled');

You're disabling ALL the inputs, including, I'd guess, the ones whose data the form is supposed to submit.

To disable just the submit button(s), you could do this:

$('button[type=submit], input[type=submit]').prop('disabled',true);

However, I don't think IE will submit the form if even those buttons are disabled. I'd suggest a different approach.

A jQuery plugin to solve it

We just solved this problem with the following code. The trick here is using jQuery's data() to mark the form as already submitted or not. That way, we don't have to mess with the submit buttons, which freaks IE out.

// jQuery plugin to prevent double submission of forms
jQuery.fn.preventDoubleSubmission = function() {
$(this).on('submit',function(e){
var $form = $(this);

if ($form.data('submitted') === true) {
// Previously submitted - don't submit again
e.preventDefault();
} else {
// Mark it so that the next submit can be ignored
$form.data('submitted', true);
}
});

// Keep chainability
return this;
};

Use it like this:

$('form').preventDoubleSubmission();

If there are AJAX forms that should be allowed to submit multiple times per page load, you can give them a class indicating that, then exclude them from your selector like this:

$('form:not(.js-allow-double-submission)').preventDoubleSubmission();

How To Prevent Double Submit With Form Validation

You can change the button type to button, and add a class to the form when it is initially submitted. If the class is present then do not submit the form. This prevents disabling the button.

See the below example using jQuery. Note that this assumes your validation is preventing the form from being submitted.

$("#status").click(function() {    if(!$("form").hasClass("submitted")){      $("form").addClass("submitted");      $("form").submit();    }});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action=""> <input type="text"/> <button id="status" type="button" value="Submitted">Submit</button></form>

Prevent double form submission

Instead of binding the submit event of FORM, try using the click handler of submit button and used:

$('form :submit').click( function () {
$(this).prop("disabled", true).closest('form').append($('<input/>', {
type: 'hidden',
name: this.name,
value: this.value
})).submit();
});

How can I prevent a double submit with jQuery or Javascript?

How about disabling the button on submit? That's what I do. It works fine.

$('form').submit(function(){
$('input[type=submit]', this).attr('disabled', 'disabled');
});

Disclaimer:

This only works when javascript is enabled on the user's browser. If the data that's being submitted is critical (like a credit card purchase), then consider my solution as only the first line of defense. For many use cases though, disabling the submit button will provide enough prevention.

I would implement this javascript-only solution first. Then track how many duplicate records are still getting created. If it's zero (or low enough to not care), then you're done. If it's too high for you, then implement a back-end database check for an existing record.

How to prevent double form submit without losing any data?

Here's an implementation that seems to be robust enough for production use:

    // prevent double submit and display a nice animation while submitting
$(document).on("submit", "form", function(event)
{
$(this).find("input[type=submit], button").each(function()
{
var $button = $(this);

if ($button.attr("disabled"))
return; // this button is already disabled, do not touch it

setTimeout(function()
{
$button.attr("disabled", "disabled");
$button.addClass("submitting");
setTimeout(function()
{
$button.removeAttr("disabled");
$button.removeClass("submitting");
}, 10000); // remove disabled status after timeout (ms)
}, 0); // let the event loop run before disabling the buttons to allow form submission to collect form data (and emit "formdata" event) before disabling any buttons and hope that user is not fast enough to double submit before this happens
});
});

The setTimeout(..., 0) is a hack to allow Chrome to run its event loop once to get Chrome to collect the form data before we disable the buttons which would drop the info about the button from the submitted data. As far as I know, this is not racy with user input because we can use delay of 0 here and there's no way for user to enter any input with zero delay.

Jquery prevent multiple submit

Bind and unbind are deprecated in JQuery.

As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document.

http://api.jquery.com/on/

To answer your question about multiple submits, another new addition in JQuery 1.7 is the .one() handler which, attaches an event handler to an object but only allows it to be fired once. This will allow you to prevent multiple submits.

e.g:

$("form#form1").one("submit", submitFormFunction);

function submitFormFunction(event) {
event.preventDefault();
$("form#form1").submit();
}

Note I'm binding to the form submit event rather than a button click event.

Prevent double submission AND allow required fields

Instead of disabling the button in the onclick attribute of the button, disable it in the onsubmit attribute of the form.

You need to give the submit button a name, and then you can refer to it as this.<name> in the onsubmit attribute. Or you could give it an ID, then you could use document.getElementById("<id>") to refer to it.

<form action="NextPage.php" method="post" onsubmit="this.submitButton.disabled = true;">  <input type="email" name="contact[email]" required id="frmEmailA" autocomplete="email">  <button type="submit" name="submitButton">Submit</button></form>

Prevent Double Submission

You can replace your code with this:

onclick="this.disabled = true; form.submit();"

the form.submit(); will do the job for you

Preventing the double submit problem in Ajax form

First, you can disable the submit button when the form is submitted. This prevent any unnecessary further form submission.
Then remove the disabled attribute once the ajax request is completed via jqXHR.always() method.

You can also change the button's text to Sending Message... for the user to know that the form is submitting.

Kindly change this part <!-- AJAX form messaging --> to this

$(function() {

// get the form
var form = $('#modal-contact-form');

// get the messages element
var formMessages = $('#modal-contact-form-responses');

// get the submit button
var submitButton = $("#modal-contact-form-submit");

// set up event listener for contact form
$(form).submit(function(e) {
// disable html submit button
e.preventDefault();

// serialize form data
var formData = $(form).serialize();

// disable submit button to prevent unnecessary submission
submitButton.attr('disabled', 'disabled');
submitButton.text('Sending Message...'); // this help the user to know that the form is sending

// submit form using AJAX
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// make sure formMessages element has 'success' class
$(formMessages).removeClass('error');
$(formMessages).addClass('success');

// set message text
$(formMessages).text('Your message has been sent. Thank you!');

// clear form
$('input, textarea').val('');
$("#modal-contact-form-message").trigger('change');
})
.fail(function(data) {
// make sure formMessages element has 'error' class
$(formMessages).removeClass('success');
$(formMessages).addClass('error');

// set the message text
$(formMessages).text('Input error. Please review and re-submit.');
}).always(function(data) { // this will always fire even if the request fails
submitButton.removeAttr('disabled');
submitButton.text('Send Message');
});

});
});


Related Topics



Leave a reply



Submit