5

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

            });

       }
   });
1
  • 2
    Tried adding e.preventDefault() above if (e.isDefaultPrevented()) ? Commented Mar 22, 2015 at 16:13

1 Answer 1

13
+100

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.