Search code examples
htmltwitter-bootstrapformsvalidationbootstrapvalidator

Having issues while running bootstrap validator along with ajax


I have a signup form on which i wish to apply bootstrap validator and if the form is filled successfully it should go to the ajax part where the backend script will run and data gets submitted.

Form

<form data-toggle="validator" role="form"  id="signup-form" method="post">

    <input type="text" class="form-control" placeholder="Name" name="cname" id="cname" required>

    <input id="email" type="email" class="form-control" placeholder=" email" name="email" data-error="email address is invalid" required>

     <input type="password" class="form-control out-box" placeholder="Password" name="password" id="password" required>

    <button type="submit" class="btn btn-primary" id="submit_form">SIGN UP</button>

</form>

Ajax Code

$("#submit_form").click(function()
  {
    var cname = $("#cname").val();
    var email = $("#email").val();
    var password = $("#password").val();
    var dataString = 'cname='+ cname + '&email='+ email + '&password='+ password ;

    $.ajax({
      type: "POST",
      url: "<?php echo base_url(); ?>/student/register",
      data: dataString,
      cache: false,
      success: function(result){
        console.log(result);     
    }});
    return false;
  });

Issue is that, if the form is empty or has any issues and i hit submit button, the problematic area gets highlighted as it haapens in bootstrap validator, but after that ajax code is also executed.

I want that the ajax code should only run when all the validations are fullfilled and the form has no issues.


Solution

  • Try the following way.

    $('#signup-form').validator().on('submit', function (e) {
      if (e.isDefaultPrevented()) {
        // handle the invalid form...
      } else {
        // everything looks good!
         var cname = $("#cname").val();
        var email = $("#email").val();
        var password = $("#password").val();
        var dataString = 'cname='+ cname + '&email='+ email + '&password='+ password ;
    
        $.ajax({
          type: "POST",
          url: "<?php echo base_url(); ?>/student/register",
          data: dataString,
          cache: false,
          success: function(result){
            console.log(result);     
        }});
        return false;
      }
    })