简体   繁体   中英

how to submit form with ajax after remote validation with jquery validation plugin

I have a form that I used jquery remote to check existing data, It check successfully, but after completing to fill the form I need to save data to the database. But submitHandler seems to not working. Here is my sample code

// html form

        <form action="save.php" method="post" id="createForm">
            <div class="input-field">
                <label for="name">Name</label>
                <input type="text" name="name" id="name">
            </div>
          <div class="input-field">
            <label for="name">Email</label>
            <input type="text" name="email" id="email">
          </div>
            <button>save</button>
        </form>

// jquery validation

      $('#createForm').validate({
          onkeyup: false,
          rules: {
              name: { required: true },
              email: {
                  required: true,
                  remote: {
                      url: 'check_email.php',
                      type: 'post',
                      dataType:'json',
                      dataFilter: function(data){let obj = eval('('+data+')'); return obj.valid; },
                      data:{email: function(){ return $('#email').val(); } }
                  }
              }
          },
          messages: {
              name: { required: "Enter a name." }
              email: { required: "Enter a email.", remote: "{0} This email exists." }
          },
          submitHandler: function(form) 
          {
                $.ajax({
                   url : $(form).attr('action'),
                   method: 'post',
                   data: $(form).serialize(),
                   dataType: 'json',
                   success: function(data){
                      show_data();
                   }
                });
          }
      });

I found a solution, When using csrf token to auto generate, jquery remote validation its we can use ajaxSetup({async: false}) before jquery validation plugin initialized, or we can set remote:{ async: false }, and avoid using contentType:false by removing it. This will prevent double request caused by remote url that ingones form action url.

   ajaxSetup({
      async: false
   });

or

       rules: {
          email: {
              required: true,
              remote: {
                  url: 'your url',
                  type: 'post',
                  async:false,
                  dataType:'json',
                  dataFilter: function(data){let obj = eval('('+data+')'); return obj.valid; },
                  data:{}
              }
          }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM