Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Bootstrap validator.js with Jquery ajax form post

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 );

            });

       }
   });
like image 225
Acyra Avatar asked Mar 22 '15 15:03

Acyra


1 Answers

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

like image 178
Dhiraj Avatar answered Nov 09 '22 21:11

Dhiraj