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

时间:2014-10-08 05:38:47

标签: 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>

3 个答案:

答案 0 :(得分:0)

通常ajax用于异步调用。

使用&#39; async&#39;在ajax电话中。脚本将一直等到ajax调用完成。

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

或者你可以在提交后在你的php中验证相同的内容..

答案 1 :(得分:0)

问题在于,您的代码将继续运行而无需等待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

         }
     });
   }
 }

答案 2 :(得分:-1)

您也可以这样做。 SOURCE

<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

            }
        });
    }
});