I have two submit handlers, one validating a form and one submitting the form:
// validates the form but does not submit it
$("form").submit(function() {
// perform validation here and set "validationFails" appropriately
// ...
if (validationFails) {
return false;
}
});
// submits the form via ajax
$("form").submit(function(event) {
event.preventDefault();
// submit the form via ajax here
// ...
});
It seems like the form should not be submitted via ajax if validation fails because return false
is used, and so the subsequent submit
handler in the chain should not be called. However, even if validation fails, the form is submitted via ajax. Why?
Use JQuery to Prevent Multiple Form Submissions To prevent the user from submitting a form multiple times, we'll use JQuery to listen for the submission event. Once the form is submitted, we'll add a disabled attribute to the button to prevent multiple form submissions. Now the user can't click it again.
attr('disabled', true). html("Processing...");" inside beforeSend() function on ajax. Then in the success() function on ajax a remove the disabled attribute/function so that the button will be clickable again after being submitted to the server.
Returning false
from an event handler is the equivalent of calling both event.preventDefault()
and event.stopPropagation()
, that is, it prevents the default action for the event from happening and it stops the event bubbling up the DOM tree. It does not stop other handlers on the same element from running.
You need to call the event.stopImmediatePropagation()
method - that stops other handlers bound to the same element from running, noting that the handlers will be run in the same order they are bound so you (obviously) have to bind your validation handler first.
$("form").submit(function(event) {
// perform validation here and set "validationFails" appropriately
// ...
if (validationFails) {
event.stopImmediatePropagation();
return false;
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With