Ajax验证在表单提交事件中中断表单提交

时间:2014-11-21 18:37:40

标签: php jquery ajax json forms

您好我的表单重定向到其操作目标有问题,验证ajax中断表单重定向这里是我的代码,所有我只是提交帖子以形成操作位置也重定向该位置。

$("form").submit(function(e){
  jQuery.ajax({
     type : "post",
     url : "validate.php",
     dataType : "json",
     data : {email : 'example@domain.com'},
     success: function(response) { 
        if(response.status == '1'){
          //Email is valid want to continue form submit and redirect , but it is not 
        }else{
           e.preventDefault();
           //return false
        }
     }
  });
})

1 个答案:

答案 0 :(得分:2)

您可能需要创建一个单独的功能 作为验证ajax进程的回调并传递序列化的数据,如:

submit

注意我们已将选择器(function submitForm(serializedData) { jQuery.ajax({ ur: "{your form action processing file}", type: "POST", data: serializedData, success: function (data, textStatus, xhr) { console.log("form submitted "+xhr.status) // 201 if everything OK // optionally reload the page window.location.reload(true); } }); } jQuery(document).ready(function ($) { // validate form $("#myForm").on("submit", function (event) { // prevent form from being submitted event.preventDefault(); // collect your form data to be submitted : var serializedData = $("#myForm").serializeArray(); $.ajax({ url : "validate.php", type: "POST", cache: false, dataType : "json", data : {email : 'example@domain.com'}, success: function (response) { if(response.status == '1'){ // email is valid so submit the form submitForm(serializedData); } // you don't need an else statement since we already used event.preventDefault() before the ajax call }, error: function () { console.log("ajax validation error"); } }) }); // on submit }); // ready )分配给我们正在处理的表单