Using Bootstrap validator.js with jquery ajax form post

I am trying to use this https://github.com/1000hz/bootstrap-validator validator to validate on the client side, and then allowing the ajax view of the entire form. I cannot find an example in the docs, and my current code is not working, it reloads the whole page with the values ​​as a GET request string. Any suggestions? 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 ); }); } }); 
+5
source share
1 answer

Add e.preventDefault() to the else statement.

If you look at # 227 in the source code , the validator will prevent the form from being submitted if the form is invalid. Therefore, e.isDefaultPrevented() can be used to check if the form is invalid.

The form action is executed by default if the form is valid, which submits the form (why reloading the page). Since you need to do ajax, you have to stop the default action on 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 the demon

Hope this helps

+11
source

Source: https://habr.com/ru/post/1215871/


All Articles