I am using jQuery Validate to validate my forms. At each validation, I use submitHandler
to submit the form via ajax to my controller (I’m using asp.net core 3.1, but I don’t think it’s that relevant). However, by double-clicking the submit button, my application performs two entries with the same data. The same thing happens with multiple enter.
I’ve researched different solutions and none of them worked for me so far. Some of them were:
jQuery preventing form from being submited twice and on enter key
Prevent double form submission
Prevent AJAX form from submitting twice?
Prevent submit form twice with change event
Most of my forms are in a modal, maybe that motivated such an action, but I still couldn’t find a valid solution. So here’s a sample source code from one of the forms – all the others use a similar structure:
THE MODAL WITH FORM
<div class="modal fade" id="modal-user-test" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">New Test</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Fechar">
<span aria-hidden="true">×</span>
</button>
</div>
<form id="form-user-test" autocomplete="off">
<div class="modal-body">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control form-control-sm" name="Name" placeholder="Name" maxlength="120" autocomplete="off" />
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline-warning" data-dismiss="modal">Back</button>
<button class="btn btn-outline-success" type="submit">Salve</button>
</div>
</form>
</div>
</div>
</div>
THE JS TO VALIDATE:
$(document).ready(function() {
$("#form-user-test").validate({
rules: {
Name: {
required: true,
minlength: 2
}
},
messages: {
Name: {
required: "The name is required",
minlength: "Enter at least two characters"
}
},
submitHandler: sendFormUserTest
});
});
THE FUNCTION FOR SUBMITTING FORM:
function sendFormUserTest(form) {
$.ajax({
url: `/User/Save`,
type: "POST",
dataType: "json",
data: $(form).serialize(),
success: function (resposta) {
messageSuccess(resposta.Message);
$("#modal-user-test").modal("hide");
},
error: showErrorMessage
});
}
I have tried using event.stopPropagation()
, event.preventDefault()
, in different places, such as before calling the valite method in document ready
, within the form submission function, but no solution was helpful to me.
I would like to inform you of a solution without marking this question as duplicate, as as I quoted twice, no solution has worked so far.
3
Answers
Not only twice, if you click it thrice it will be submitted thrice, that also goes for n number of clicks.
You need to disable the
submit button
when the form is being submitted and enable the button when$.ajax
calls success or error callback.Try to use my approach. hopefully, this can help. 🙂