How to check if the connection dropped before sending a data via ajax?

1
var erroEnvio = false; //global

$(".proxima-questao").on("click",function(){
    $(".loading").show();
    $.ajax({
        url: urlBase+"123123123/adasdasdasdas",
        type: "POST",
        data: $("#form").serialize(),
        success:function(resposta){
            if(resposta === "sucesso"){
                erroEnvio = false;
                setSuccessEnvio(erroEnvio);
                $(".loading").hide();
            } else {
                erroEnvio = true;
                setSuccessEnvio(erroEnvio);
                $(".loading").hide();
            }
        }
    });
});

function setSuccessEnvio(x){
    erroEnvio = x;
}


 if(erroEnvio === false) {
    // a idéia é salvar os dados antes de ir pro próximo bloco
    proximaQuestao();
} else {
    alert("Erro");
}

    if($stmt->execute()){
        return "sucesso";
    } else {
        return "falha";
    }

One thing I noticed is that it is returning success even with the dropped connection.

When I go offline, I can go to the next question, after I'm in the next block, if I click again on botão próxima questão it shows this Error alert.

    
asked by anonymous 29.04.2016 / 20:16

1 answer

1

It is not in success that you should check for any connection or error errors on the server side, you should use the .error of the ajax itself.

If you are using the jQuery version equal to or less than 1.8, use success and error as follows:

$.ajax({
   type: 'POST',
   url: 'arquivo.php',
   dataType: 'json',
   success: function (data) {
      console.log(data);
   },
   error: function (jqXHR, textStatus, errorThrown) {
      // Informe aqui que a conexão caiu ou que houve algum problema
      console.log(jqXHR);
      console.log(textStatus);
      console.log(errorThrown);
   }
});

If it is above 1.8 use done and fail:

$.ajax({
   type: 'POST',
   url: 'arquivo.php',
   dataType: 'json',
   done: function (data) {
      console.log(data);
   },
   fail: function (jqXHR, textStatus, errorThrown) {
      // Informe aqui que a conexão caiu ou que houve algum problema
      console.log(jqXHR);
      console.log(textStatus);
      console.log(errorThrown);
   }
});

Tip: You can use beforeSend and complete to put your load image and create a generic function to do these requests using then:

 var request = function(url, data) {
   return $.ajax({
     type: 'POST',
     url: url,
     data: data,
     dataType: 'json',
     beforeSend: function() {
       $("img").show();
     },
     complete: function() {
       $("img").hide();
     },error: function(data) {
        $("div").append(data.statusText);
     }
   });
 };


 request("https://baconipsum.com/api/?type=meat-and-filler").then(function(data) {
   $("div").append(data);
 });

Example: jsfiddle

    
29.04.2016 / 20:37