Maxence
Maxence

Reputation: 2339

Retry ajax call until successful

I have an Ajax call that I would like to retry when failing, based on this current code :

$.ajax({
        url: "<%= my_ruby_on_rails_controller_url_here %>",
        datatype: "json",
        type: "GET",
        success: function (json) {
            document.getElementById("factureload" + json.hashed_id).innerHTML = "<a href='" + json.address + "'><img class='pdficonstyling' src='/assets/pdf4.svg' alt='pdf icon' /> facture_" + json.numfacture + "</a>";
        },
        error: function () {
            alert("fail");

        }
    });

I have tried to encapsulate it inside a new function with a callback to this function in error (together with setTimeout) but it never starts ...

Also There could be concurrent Ajax calls such as this one for different dom elements.

(there is this useful thread but I am so bad in JS I cannot adapt it to my code How to repeat ajax call until success )

Upvotes: 3

Views: 4933

Answers (2)

djfdev
djfdev

Reputation: 6037

That link you posted contains the exact answer ... you just need to wrap your code in a function so it can be used recursively:

function myAjaxRequest () {
  $.ajax({
    url: "<%= my_ruby_on_rails_controller_url_here %>",
    datatype: "json",
    type: "GET",
    success: function (json) {
      document.getElementById("factureload" + json.hashed_id).innerHTML = "<a href='" + json.address + "'><img class='pdficonstyling' src='/assets/pdf4.svg' alt='pdf icon' /> facture_" + json.numfacture + "</a>";
    },
    error: function () {
      setTimeout(() => {
        myAjaxRequest()
      }, 5000) // if there was an error, wait 5 seconds and re-run the function
    }
  })
}

myAjaxRequest()

Upvotes: 8

Charlie Martin
Charlie Martin

Reputation: 8406

function tryUntilSuccess(success) {
   $.ajax({
      url: '<%= my_ruby_on_rails_controller_url_here %>',
      datatype: 'json',
      type: 'GET',
      success: success,
      error: function(err) {
          console.log('Request failed. Retrying...', err)
          tryUntilSuccess(success)
     },
  })
}

tryUntilSuccess(function onSuccess(json) {
    document.getElementById("factureload" + json.hashed_id).innerHTML = "<a href='" + json.address + "'><img class='pdficonstyling' src='/assets/pdf4.svg' alt='pdf icon' /> facture_" + json.numfacture + "</a>";
})

Upvotes: 0

Related Questions