hitautodestruct hitautodestruct - 3 months ago 17x
jQuery Question

How do I resend a failed ajax request?

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
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)


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 perform 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 writer

// 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 );

      // else... Call AJAX again with original options
      $.ajax( originalOptions);