使用jquery验证的ajax表单提交

时间:2016-09-23 09:41:57

标签: jquery ajax validation

我尝试使用带有jQuery验证的AJAX提交我的联系表单。我认为传递表单数据存在错误。验证工作正常,但AJAX的问题是我无法解决的。请查看下面的代码并帮我解决它。

$(document).ready(function(){
    $('#test-form').validate({
        rules: {
            name:{
                required: true,
            },
            org: {
                required: true,
            },
            email: {
                required: true,
                email:true,
                maxlength: 50,
            },
            phone:{
                number:true
            },
            message:{
                required: true,
            }
        },
        messages: {
            name: {
                required:"Enter Your Name",
            },
            org: {
                required:"Enter Your Organisation",
            },
            email: {
                required: "Enter Your Email Address",
                email: "Enter correct email format",
            },
            phone:{
                number : "Phone number must contain digits only",
            },
            message:{
                required: "Enter Your Message",
            }
        },
        submitHandler: function(form, e) {
            e.preventDefault();
            alert('three');

            var This = $(this);
            var action = $(This).attr('action');
            var data_value = unescape($(This).serialize());

            $.ajax({
                type: "POST",
                url: action,
                data: data_value,
                success: function(response) {
                    $('#ajax_contact_msg').html(response);
                }            
            });
            return false;
        }
    });
});

1 个答案:

答案 0 :(得分:0)

而不是使用submitHandler事件使用jquery validate的.valid()函数。只有当所有表单字段都符合验证时才允许ajax调用。

请检查以下代码。

$(document).ready(function(){
  $('#test-form').validate({

    rules: {
      name:{
        required: true,
      },

      org:{
        required: true,
      },

      email:{
        required: true,
        email:true,
        maxlength: 50,

      },
      phone:{
        number:true
      },
      message:{
        required: true,
      }


    },
    messages: {
      name: {
        required:"Enter Your Name",
      },

      org: {
        required:"Enter Your Organisation",
      },

      email: {
        required: "Enter Your Email Address",
        email: "Enter correct email format",
      },
      phone:{

        number : "Phone number must contain digits only",
      },
      message:{
        required: "Enter Your Message",
      }

    }
  });
});

if($('#test-form').valid()){
  alert('three');

  var This = $(this);

  var action = $(This).attr('action');
  var data_value = unescape($(This).serialize());
  $.ajax({
    type: "POST",
    url:action,
    data: data_value,

    success: function(response) {
      $('#ajax_contact_msg').html(response);
    }            
  });
  return false;
}