2016-09-23 138 views
0

我想提交我的聯繫表單使用AJAX與jQuery驗證。我認爲傳球數據存在錯誤。驗證工作正常,但AJAX無法解決問題。請在下面查看我的代碼並幫助我理清它。ajax表單提交與jQuery驗證

$(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; 
     } 
    }); 
}); 
+0

檢查您的控制檯是否有錯誤。你發送的data_value的值是多少?另外請注意,不需要將'This'放在jQuery對象中 - 它已經是一個 –

回答

0

而不是使用submitHandler事件中使用JQuery驗證的.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; 
} 
+0

這意味着標準表單提交仍然會發生,因此AJAX請求將無法正確完成。使用'submitHandler'是正確的方法。 –