Where The Streets Have No Name

jquery ajax error handling 본문

Developement/Web

jquery ajax error handling

highheat 2011. 7. 21. 12:16
출처 : http://www.maheshchari.com/jquery-ajax-error-handling/

jQuery is the most awesome javascript library that made easy for asynchronous ajax calls.it has global ajaxfunction and some pre defined ajax functions like $.get$.post, load .etc. but we don’t find any error messagesby 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 jQueryby default. We can set many options,to see available ajaxsetup options please check here.

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

Example1

1
2
params={name:'mahesh'};
$.get(url,params,function(){})

In above example,jQuery automatically raises all available errors,except parse error. because we didn’t give any return type format.

Example2

1
2
3
params={name:'mahesh'};
$.get(url,params,function(){},'json');
$.getJSON(url,params,function(){});

In above example,jQuery automatically raises all available errors,because we added return type format at end. $.getJSON automatically adds the return type of parameter to “JSON”

Example3

1
2
params={name:'mahesh'};
$.get(url,params,function(){},'xml');

In the above example 3 ,we gave xml type return parameter, here also jQuery automatically raises all errors even parse error also.