使用ajax和jquery防止根据ajax中的条件提交表单



我用php、ajax和jquery提交了表单。我想根据ajax条件阻止表单提交。但不要停止提交表格。有任何机构对这些问题给出任何解决方案吗?我的代码在下面

   <script>
   function validate_form()
   {
   var sale_type= $('#sale_type').val();
   var cust_name=   $('#cust_name').val();
   if(sale_type=='credit')
    {
      alert("msg"); 
      $.ajax({
      type: "POST",
      url: 'ajx_validation_due_date.php',
      data:'cust_name='+cust_name,
      success: function(msg)
      { 
      alert(msg);
      if(msg==0)
      {
        alert("You cant add sale,Due days is completed");
        preventDefault();
        return false;      
      }
    }
   }); 
  }
  }
  </script>
 <form action="" method="post" name="adFrm" onSubmit="return validate_form()">
 </form>

通常ajax用于异步调用。

在ajax调用中使用"async"。脚本将等待ajax调用完成。

     $.ajax({
           type: "POST",
           url: 'ajx_validation_due_date.php',
           data:'cust_name='+cust_name,
           async : false,
           success: function(msg)
           { 
                // Your code
           }
     });

或者,您可以在提交后在php中验证相同内容。。

问题是,您的代码将在不等待ajax调用完成的情况下进一步运行,返回undefined,因此将进行表单提交。

相反,请使用event.preventDefault()阻止默认表单提交,并手动提交。

<form action="" method="post" name="adFrm" onSubmit="validate_form(event)">

 function validate_form(event) {
   event = event || window.event;
   event.preventDefault(); // prevent submission
   var sale_type = $('#sale_type').val();
   if (sale_type == 'credit') {
     alert("msg");
     $.ajax({
         type: "POST",
         url: 'ajx_validation_due_date.php',
         data: 'cust_name=' + cust_name,
         success: function (msg) {
             alert(msg);
             if (msg == 0) {
                 alert("You cant add sale,Due days is completed");  
                 return false;
             }
             else
                 $("[name='adFrm']")[0].submit(); // submit the form manually upon success
         }
     });
   }
 }

您也可以这样做。源

<form action="" method="post" name="adFrm" id="adFrm" >
</form>

$("#adFrm").submit(function(e)
{
    e.preventDefault(); //STOP default action
    e.unbind(); //unbind. to stop multiple form submit ,
    // and if you again submit , it won't go through this process again.
    var sale_type = $('#sale_type').val();
    if (sale_type == 'credit') {
        alert("msg");
        $.ajax({
            type: "POST",
            url: 'ajx_validation_due_date.php',
            data: 'cust_name=' + cust_name,
            success: function(msg) {
                alert(msg);
                if (msg == 0) {
                    alert("You cant add sale,Due days is completed");
                    return false;
                }
                else
                    $("#adFrm").submit(); // note: i have unbinded the submit, so it will simply submit, instead of going through all
            }
        });
    }
});

最新更新