.ajaxError()S2C Home « Ajax « .ajaxError()

Ajax global error handler.

Description

The .ajaxError() Ajax method, allows us to register an Ajax Event handler to be called when Ajax requests complete with an error.

  • The .ajaxError() method callbacks are executed via the ajaxError event which is triggered every time an Ajax request completes with an error. For finer grained control of callback execution when the .ajaxError() Ajax method is fired, interrogate the event and jqXHR objects or the ajaxSettings or thrownError parameters passed to the method.

Syntax

Signature Description
.ajaxError( handler(event, jqXHR, ajaxSettings, thrownError) )Register an Ajax Event handler to be called when Ajax requests complete with an error.

Parameters

Parameter Description Type
handler( event, jqXHR, ajaxSettings, thrownError ) The function to be called.
  • Each time the callback runs, it is passed the event and jqXHR objects as well as the ajaxSettings and thrownError pertaining to the request.
  • The callback is fired in the context of the current jQuery instance, so the this special operator refers to that instance.
Function

Return

A jQuery object.

.ajaxError( handler(event, jqXHR, ajaxSettings, thrownError) ) ExampleTop

Register an Ajax Event handler to be called when Ajax requests complete with an error.

In the example below when we press the button the first time, we use the .ajaxError() method to set up a global event handler to be run for each Ajax request. The handler is fired at the end of each request that finishes with an error. In this case the handler outputs a message giving some information about the request error.


$(function(){
  $('#btn2').one('click', function(){
    // Register global event handler and attach to 'div2' element
    $('#div2').ajaxError(function(event, jqXHR, ajaxSettings, thrownError) {
       $(this).append('Triggered the ajaxError() global event handler for url: ' 
                      + ajaxSettings.url + '. Status: ' + jqXHR.status + '. Status text: ' 
                      + jqXHR.statusText + '. Error: ' + thrownError + '.<br><br>');
    });
    $.ajax( "../js/get2.js", {
      dataType: "script",
      success: function() { 
        $('#div2').append('The request was a success! <br>');
      }
    });
    $.ajax( "../js/get22.js", {
      dataType: "script",
      success: function() { 
        $('#div2').append('The request was a success! <br>');
      }
    });
    $.get( "../js/get4.js" );
    $.post( "../js/post2.js" );
  });
});

div2. Some initial text.

Press the button below to action the above code: