How to repeat an ajax query that gave error?

3

The problem is that sometimes the query runs out of time or gives a real error, so I want to automate it.

$.ajax({
            type: "GET",
            url: 'inserindodados.prisma',
            data: $('#FormularioDescoberta').serializeArray(),
            dataType: "json",
            success: function(sucesso){
            // Beleza deu certo!
            }
            error: function(erro){
            // Tente novamente
            }

});
    
asked by anonymous 20.08.2017 / 21:42

1 answer

3

Put a function around to be able to self-invoke.

I made an example where you wait 0.5 seconds before the next attempt and receive a maximum of attempts.

You can do the most advanced thing with setTimeout to interrupt if it takes too long, but in the example I considered just the case of calling the error callback.

Example:

function ajax(dados, nrTentativas, cb) {
  $.ajax({
    type: "GET",
    url: 'inserindodados.prisma',
    data: dados,
    dataType: "json",
    success: function(sucesso) {
      // Beleza deu certo!
      cb(null, sucesso);
    }
    error: function(erro) {
      // Tente novamente
      if (nrTentativas > 0) setTimeout(ajax.bind(null, dados, nrTentativas - 1, cb), 500);
      else cb(erro);
    }

  });
}

var dados = $('#FormularioDescoberta').serializeArray();
ajax(dados, 5, function(err, resposta) {
  if (err) return console.log(err);
  console.log(resposta);
});
    
20.08.2017 / 21:48