While making ajax calls using jQuery we generally need to take care of the errors that are encountered while making these calls.
This article describes the different ways of handling errors during Ajax call using jQuery.
jQuery Ajax error handling
jQuery provides with a function ajaxError which gets triggered when a ajax calls fails.
ex.
1 2 3 |
$( document ).ajaxError(function() { $( "your error div" ).text( "Your Error Message" ); }); |
Since a ajax call can fail for many reasons, to catch a specific failure we can get information about the failure using the below parameters to the ajaxError function
event, jqxhr, settings, thrownError
a. event
event param contains the event object.
b. jqxhr
jqxhr param contains the jQuery XMLHttpRequest object.
c. settings
settings param contains the options or setting that were used during the request.
d. thrownError
If the ajax call fails due to HTTP error, the param thrownError receives the textual portion of the HTTP status
ex. “Internal Server Error.”
If $.ajax() or $.ajaxSetup() is called with the global option set to false, the .ajaxError() method will not fire.
Ajax error function
$.ajax() method also contains an error method that gets called when a ajax method fails.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
$.ajax({ url: "server_url", success: function(data){ //process or display data }, error: function(jqXHR, textStatus, errorThrown) { if(jqXHR.responseText !== '') { alert(textStatus+": "+jqXHR.responseText); } else { alert(textStatus+": "+errorThrown); } } }); |
Details of the error function params
a. jqxhr
jqxhr param contains the jQuery XMLHttpRequest object.
b. textStatus
Possible values for the textStatus param are “timeout”, “error”, “abort”, “parsererror” and null.
c. errorThrown
If the ajax call fails due to HTTP error, the param errorThrown receives the textual portion of the HTTP status
ex. “Internal Server Error.”
Please do let me know if you need any more info in this or any articles available on this site.