在AJAX检查后提交表单

时间:2017-01-24 10:56:41

标签: php jquery html ajax

这是我的代码:

$('#form').on('submit', function(e) {
  var form = this;
  e.preventDefault();

  if (($('#datepicker').val() == '') || ($('#heureDebut').val() == '') || ($('#heureFin').val() == '') || ($('#rechercheVilleChargement').val() == '') || ($('#rechercheVilleChargementDPT').val() == '') || ($('#rechercheVilleLivraison').val() == '') || ($('#rechercheVilleLivraisonDPT').val() == '') || ($('#numeroCommande').val() == '') || ($('#numeroOT').val() == '') || ($('#affrete').val() == '') || ($('#client').val() == '') || ($('#depot').val() == '')) {
    swal({
      title: "Erreur",
      text: "Des champs obligatoires sont vides, complétez ces champs puis validez. ",
      type: "error",
      confirmButtonText: "Retour au formulaire",
      confirmButtonColor: "#333570"
    });
    return false;
  } else {
    $.ajax({
      type: "POST",
      url: "MODEL/ajaxCheckAddTransport.php",
      cache: false,
      data: $("#form").serialize(),
      success: function(data) {
        alert(data);
        if (data == "NO") {
          return true;
        } else {
          swal({
            title: "Erreur",
            text: "L'OT " + ($('#numeroOT').val()) + " existe déjà. Impossible de créer le transport.",
            type: "error",
            confirmButtonText: "Retour au formulaire",
            confirmButtonColor: "#333570"
          });
          return false;
        }
      },
      error: function() {
        alert('La requête AJAX n\'a pas abouti, contactez l\'administrateur');
      }
    });
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='container'>
  <form class="form-horizontal" role="form" method="post" action="MODEL/addTransport.php" id="form">
    <div class='row'>
      <div class="col-lg-6">
        <div class="titleprghp text-center">
          <span class="prg">Chargement</span> 
        </div>
      </div>
      <div class="col-lg-6">
        <div class="titleprghp text-center">
          <span class="prg">Livraison</span>
        </div>
      </div>
    </div>

一切都好,我从AJAX查询中得到正确的值,“NO”和“YES”,当我必须得到它时。问题是,当我得到“NO”值时,我无法提交表单......

if (data == "NO")
{
   return true;
}   

这是我的问题......

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

您遇到的问题是您已使用preventDefault()停止表单提交。另外,在AJAX回调中使用return是没有意义的,因为它根本不会影响外部submit处理程序。

要解决此问题,请直接调用基础submit()的{​​{1}}方法。试试这个:

form

Simplified example

我还强烈建议您将success: function(data) { if (data == "NO") { form.submit(); // use the 'form' variable you created within the submit hander here... } else { swal({ title: "Erreur", text: "L'OT " + $('#numeroOT').val() + " existe déjà. Impossible de créer le transport.", type: "error", confirmButtonText: "Retour au formulaire", confirmButtonColor: "#333570" }); } }, 端点更改为 NOT 返回明文响应。改为使用包含有效性状态的布尔属性返回JSON。

答案 1 :(得分:0)

试试这个

if (data == "NO")
    {
       $("#form").submit();
    } 
相关问题