jquery ajax error handling

How to handle ajax errors using jQuery ?

jQuery is the most awesome javascript library that made easy for asynchronous ajax calls.it has global ajax function and some pre defined ajax functions like $.get, $.post, load .etc. but we don’t find any error messages by default with this library. we can see the errors with firefox’s addon firebug or with IE developer toolbar.So we manage most common ajax errors in our application with global ajaxSetup function which come with jQuery by default. We can set many options,to see available ajaxsetup options.

most ajax errors we get errors are server response errors and some JSON parse errors. To know more about the HTTP errors details please check here. To test this error handling just copy and paste it to your head section of HTML document.

Javascript Code for setting global error handling.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$().ready(function(){
$.ajaxSetup({
error:function(x,e){
if(x.status==0){
alert('You are offline!!\n Please Check Your Network.');
}else if(x.status==404){
alert('Requested URL not found.');
}else if(x.status==500){
alert('Internel Server Error.');
}else if(e=='parsererror'){
alert('Error.\nParsing JSON Request failed.');
}else if(e=='timeout'){
alert('Request Time out.');
}else {
alert('Unknow Error.\n'+x.responseText);
}
}
});
});
In the above example we handle following common error and show response text for other rare errors.

  • 0-xhr status ,is it initialized or not that means user is offline.

  • 404-page not found

  • 500-Internel Server error.

  • request timeout – jQuery custom error.

  • parseerror-jQuery custom error when parsing JSON data.

  • we just throw other errors with response error

0 comments: