I'm trying to use this validator https://github.com/1000hz/bootstrap-validator for client-side checking and then allowing the ajax submission of an entire form. I can't find an example in the docs and my current code doesn't work, it reloads the whole page with the values as a GET query string. Any thoughts? Thanks!
$('#send-form').validator().on('submit', function (e) {
if (e.isDefaultPrevented()) {
// handle the invalid form...
} else {
// everything looks good!
$.post( "/post/ajax",
$( "#send-form" ).serialize(),
function( data ) {
$( "#ajax-result" ).html( data );
});
}
});
Add e.preventDefault()
in the else statement.
If you look at #227 in the source code, the validator prevents form submission if the form is invalid. Hence e.isDefaultPrevented()
can be used to check if the form is invalid.
The form's default action is carried out if the form is valid which is submitting the form (why the page reloads). Since you need to do an ajax you should stop default action by e.preventDefault()
$('#send-form').validator().on('submit', function (e) {
if (e.isDefaultPrevented()) {
alert('form is not valid');
} else {
e.preventDefault();
alert('form is valid');
// your ajax
}
});
Here is a demo
Hope this helps
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