Alan Coromano
Alan Coromano

Reputation: 26048

Resend an ajax request if case of error or error code

I a javascript function which sends an ajax request. Note that the server might return an error even if "everything seems to be ok" which means that there might be an error information in the handler of success:

function sendAjaxRequest(){
    $.ajax({
        type: "GET",
        url: "/123",
        success: function(data){
          //there might and might not an error in data
          if(data.error_exists){
              retryIfError(data);
          } else{
            //everything is ok for sure
          }
        },
        error: function(xhr, textStatus, errorThrown){
          //there is the error for sure
          retryIfError(xhr);
        }
    });
}

 function retryIfError(data){
   var error = data.error_list # the array of error messages
   // ... what should I do further?
  }

The reason is that success: function(data) might have an error is that the server uses begin ... rescue operators to suppress them. Is that the right approach?

The second question:

So the goal is to send sendAjaxRequest() until there are no errors anymore. How do I do that? Of course, I want also restrict the amount of sending sendAjaxRequest() requests, but I think it will be trivial and I'll take care of it by myself.

Upvotes: 1

Views: 608

Answers (1)

Ali Bassam
Ali Bassam

Reputation: 9969

What about calling the function again? you can add a counter as well.

error: function(xhr, textStatus, errorThrown){
            if(i<3)
            sendAjaxRequest(i++);
        }

And use.

var i=0;

Upvotes: 3

Related Questions