在通过ajax提交表单之前在ajax中进行表单验证

时间:2017-07-23 12:08:40

标签: php jquery ajax forms

我使用ajax提交表单并将值插入数据库..我尝试了很多方法,但验证错误检查没有正确。 这是我的代码

$(document).ready(function() {
  $('body').on('click', '#Submit', function(e) {
    e.preventDefault();
    var formData = new FormData($(this).parents('form')[0]);

    $.ajax({
      url: 'formrelay.php',
      type: 'POST',
      xhr: function() {

        var myXhr = $.ajaxSettings.xhr();
        return myXhr;
      },
      success: function(data) {
        document.getElementById('Message').innerHTML = data;
      },
      data: formData,
      cache: false,
      contentType: false,
      processData: false
    });
    return false;
  });
});

我尝试使用submithandler(在其中一个教程中看到)但是它没有用..请帮助..下面的代码

 $(document).ready(function(){
     $("#relay_form").validate({
       rules: {
            f_name: { required : true }
          },

        submitHandler : function (form) {
                           e.preventDefault();
            var formData = new FormData($(this).parents('form')[0]);

            $.ajax({
                url:'form_relay.php',
                type: 'POST',
                xhr: function() {

                    var myXhr = $.ajaxSettings.xhr();
                    return myXhr;
                },
                success: function (data) {
                    document.getElementById('Message').innerHTML=data;
                },
                data: formData,
                cache: false,
                contentType: false,
                processData: false
            });
            return false;
          }
    });

    });

1 个答案:

答案 0 :(得分:0)

这对我有用..

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/additional-methods.js"></script>

<!-- red color for error message -->
<style type="text/css">
  #hardship_form .error {
    color: red
  }
</style>
<script>
  $(document).ready(function() {
    $("#relay_form").validate({
      rules: {
        f_name: {
          required: true
        }
      },
      messages: {
        f_name: "Please Enter first name"
      },
      submitHandler: function(form) {
        e.preventDefault();
        var formData = new FormData($(this).parents('form')[0]);

        $.ajax({
          url: 'form_relay.php',
          type: 'POST',
          xhr: function() {

            var myXhr = $.ajaxSettings.xhr();
            return myXhr;
          },
          success: function(data) {
            document.getElementById('Message').innerHTML = data;
          },
          data: formData,
          cache: false,
          contentType: false,
          processData: false
        });
        return false;
      }
    });

  });
</script>

感谢米兰