How to repeat a failed ajax query?

Asked

Viewed 85 times

3

The problem is that sometimes the consultation runs out of time or even gives error, so I want to automate in these cases.

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

});

1 answer

3


Put a function around it so it can auto-invoke.

I made an example where you wait 0.5 seconds before the next attempt and get 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 only 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);
});

  • What would be bind(null ?

  • @Rafaellemos bind creates a new function already "configured". The first argument indicates what will be the this within this new function. The others are the parameters of the function when invoked. As I do not need to use the this placed null, but you can use something else if you want.

Browser other questions tagged

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