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

Asked

Viewed 191 times

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’s returning success even with the dropped connection.

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

  • Because you have setSuccessEnvio if its change in the erroEnvio is already going global?

  • No need to test before sending. You send and see if it worked for the return of Ajax, and take the necessary action based on this.

1 answer

1

It is not in success that you should check if there has been any connection error or error in the server part, you must use the . error of the ajax itself.

If you are using jQuery version less than or equal to 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 load your image and create a generic function to make 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.