Problem with form + ajax

1

I made an ajax request to send data from a form to the server, the data is sent and stored perfectly. But when handling success creating the condition if the return return was the 200 or "OK" pattern would send a success message and if not, the error. However, when I did this, I realized that the result was not returning because it was already falling on the else. And even if it drops ELSE, it stores the data on the server, but it throws the error message.

function sendForm()
{

  $("#divSucesso").hide();
  $("#divError").hide();

  document.getElementById("btnEnviarForm").disabled = true;
  // var formAgenda = document.getElementById("form");
  var formData = new FormData (document.forms[0]);

  $.ajax({
      url: 'insert.php',
      type: 'POST',
      async: true,
      dataType: 'html',
      data: formData,
      processData: false,
      contentType: false,

      success: function (result) {

          if (result.substring(0, 2) == "OK")
          {
            document.getElementById('divSucesso').innerHTML = "Dados salvos com sucesso: " + result;
            $("#divSucesso").stop().fadeIn(200).delay(50000).fadeOut(200);
            document.getElementById("form").reset();
          }
          else
            showMessageError(result);

          document.getElementById("btnEnviarForm").disabled = false;            
        },

      error: function (xhr, status, error) {

      showMessageError(status + error + xhr.responseText);
      document.getElementById("btnEnviarForm").disabled = false;
    }

  });

}

  function showMessageError(message)
  {
    document.getElementById("errorMsg").innerHTML = message;
    $("#divError").fadeIn(200).delay(2500).fadeOut(200);
  }
    
asked by anonymous 31.05.2018 / 01:33

1 answer

0

In jQuery Ajax, success: already means that the status tag of the return XHR was 200 . It is redundant to do a check of OK (that would be the xhr.statusText in the third return parameter) inside the callback, since it will always be "OK" in success: :

success: function (result, status, xhr){

   // result -> dados HTML de retorno
   // status -> retorna a string "success"
   // xhr    -> objeto XHR gerado

}

To get the return codes 200 and OK :

success: function (result, status, xhr){

   xhr.status; // retorna "200"
   xhr.statusText; // retorna "OK"

}
    
31.05.2018 / 01:55