13

I have multiple ajax requests some request data every minute others are initiated by the user through a ui.

$.get('/myurl', data).done(function( data ){
   // do stuff..
});

The request might fail due to an authentication failure. I've setup a global .ajaxError() method for catching any failed requests.

$(document).ajaxError(function( e, jqxhr ){
   // Correct error..
});

After I catch the error I reset authorization. Resetting the authorization works but the user has to manually re initiate the ajax call (through the ui).

How do I resend the failed request using the jqxhr originally sent?

(I'm using jQuery for the ajax)

hitautodestruct
  • 20,081
  • 13
  • 69
  • 93
  • I had to do that once. I simply stored the contents of the original `data` object *(passed to the `get` method)* somewhere safe, and reused it in a later call to `get`, invoked by a click on a `retry` button, or a timer. – Anders Marzi Tornblad Jan 16 '12 at 14:49
  • 1
    http://api.jquery.com/jQuery.ajax/ you can use a `.fail` alongside the `.done` and call your callback method from there. – Aram Kocharyan Jan 16 '12 at 14:52
  • @atornblad - This won't help since the `data` object could have been overridden by a different AJAX request that fired before this one `error`ed. – Joseph Silber Jan 16 '12 at 14:53
  • @AramKocharyan I have multiple calls besides the one that pulls every minute. I would have to append a fail to each ajax call that I make. And also define the callback as a global. – hitautodestruct Jan 16 '12 at 15:11
  • possible duplicate of [What's the best way to retry an AJAX request on failure using jQuery?](http://stackoverflow.com/questions/10024469/whats-the-best-way-to-retry-an-ajax-request-on-failure-using-jquery) – user2284570 Oct 10 '14 at 13:59

4 Answers4

12

Found this post that suggests a good solution to this problem.

The main thing is to use $.ajaxPrefilter and replace your error handler with a custom one that checks for retries and performs a retry by using the closure's 'originalOptions'.

I'm posting the code just in case it will be offline in the future. Again, the credit belongs to the original author.

// register AJAX prefilter : options, original options
$.ajaxPrefilter(function( options, originalOptions, jqXHR ) {

   originalOptions._error = originalOptions.error;

   // overwrite error handler for current request
   options.error = function( _jqXHR, _textStatus, _errorThrown ){

   if (... it should not retry ...){

         if( originalOptions._error ) originalOptions._error( _jqXHR, _textStatus, _errorThrown );
         return;
      };

      // else... Call AJAX again with original options
      $.ajax( originalOptions);
   };
});
faintsignal
  • 1,828
  • 3
  • 22
  • 30
Shai Reznik - HiRez.io
  • 8,748
  • 2
  • 33
  • 33
7

In this case, I would write a specific handler for the 403 status code, which means unauthorized (my server would return a 403 too). From the jquery ajax docs, you can do

$.ajax({
  statusCode: {
    403: function() {
        relogin(onSuccess);
    }
  }
});

to achieve that.

In that handler, I would call a relogin method, passing a function that captures what to do when login succeeds. In this case, you could pass in the method that contains the call you want to run again.

In the code above, relogin should call the login code, and onSuccess should be a function that wraps the code you execute every minute.

EDIT- based on your clarification in comment, that this scenario happens for multiple requests, I personally would create an API for your app that captures the interactions with the server.

app = {};
app.api = {};
// now define all your requests AND request callbacks, that way you can reuse them
app.api.makeRequest1 = function(..){..} // make request 1
app.api._request1Success = function(...){...}// success handler for request 1
app.api._request1Fail = function(...){...}// general fail handler for request 1

/**
  A method that will construct a function that is intended to be executed
  on auth failure.

  @param attempted The method you were trying to execute
  @param args      The args you want to pass to the method on retry
  @return function A function that will retry the attempted method
**/
app.api.generalAuthFail = function(attempted, args){
   return function(paramsForFail){ // whatever jquery returns on fail should be the args
      if (attempted) attempted(args); 
   }  
}

so with that structure, in your request1 method you would do something like

$().ajax({
    ....
    statusCode: {
        403: app.api.generalAuthFail(app.api.request1, someArgs);
    }
}}

the generalAuthFailure will return a callback that executes the method you pass in.

hvgotcodes
  • 118,147
  • 33
  • 203
  • 236
  • I've thought of doing this, the problem is that I have multiple ajax calls, not just the one going once a minute. I need a way to access the failed request from within the error and re instigate the original request. – hitautodestruct Jan 16 '12 at 15:08
  • BTW In my case we're talking about a [401](http://en.wikipedia.org/wiki/HTTP_401#4xx_Client_Error) – hitautodestruct Jan 16 '12 at 15:19
  • I understood that. What I don't understand is how I would avoid naming all my anonymous success callbacks using the above code? – hitautodestruct Jan 16 '12 at 15:31
  • @hitautodestrcut I edited my answer. basically don't use anonymous functions. – hvgotcodes Jan 16 '12 at 15:43
  • I'm trying your approach but in a more dynamic way. Instead of identifying all my callback functions I'm trying to steal the callback from the active ajax event before it goes out. If I don't succeed I will probably accept the above answer. – hitautodestruct Jan 18 '12 at 08:14
2

The code below will keep the original request and it will try to success 3 times.

var tries = 0;
$( document ).ajaxError(function( event, jqxhr, settings, thrownError ) {
    if(tries < 3){
        tries++;
        $.ajax(this).done(function(){tries=0;});
    }
});
Sabri Aziri
  • 4,084
  • 5
  • 30
  • 45
0

You could possibly go by the option of naming each one of your functions and then recalling them as stated in hvgotcodes' answers.

Or

You can use a reusable function to setup a request while extending the defaults:

function getRequest( options ){

    var // always get json
        defaults = { dataType: 'json' },
        settings = $.extend( defaults, options );


    return // send initial ajax, if it's all good return the jqxhr object
           $.ajax( settings )
           // on error
           .fail(function( jqxhr, e ){
                // if the users autherization has failed out server responds with a 401
                if( jqxhr.status === 401 ){
                    // Authenticate user again
                    resetAuthentication()
                    .done(function(){
                        // resend original ajax also triggering initial callback
                        $.ajax( settings );
                    });
                }
           });
};

To use the above function you would write something like this:

getRequest({
    url: 'http://www.example.com/auth.php',
    data: {user: 'Mike', pass: '12345'},
    success: function(){ // do stuff }
});

The getRequest() could probably be made recursive and/or converted into a jQuery plugin but this was sufficient for my needs.

Note: If the resetAutentication function might faile, getRequest() would have to be recursive.

hitautodestruct
  • 20,081
  • 13
  • 69
  • 93