Click here to Skip to main content
Click here to Skip to main content

Use ajaxSetup to Configure Error Handling on Ajax Calls in jQuery

By , 25 Jun 2010
 
$.getJSON method of jQuery does not provide any access to a method in case an error occurs while calling a page asynchronously.
 
The common use of getJSON method is:
 
$.getJSON(<<page name>>, <<paremeters>>, <<function to call on success>>);
 
In case any error occurs while calling the requested page, it does not provide any notification about the failed request.
 
In order to raise an event in case any error occurs, call $.ajaxSetup before $.getJSON.
 
$.ajaxSetup provides the facility to predefine ajax settings which will be followed with all subsequent Ajax calls.
 
$.ajaxSetup can be used like this:
 
$.ajaxSetup({ error:myfunc });
 
function myfunc(XMLHttpRequest, textStatus, errorThrown)
{
 alert('error');
}
 
$.getJSON(<<page name>>, <<paremeters>>, <<function to call on success>>);
 
 
Now, when any occurs while calling the requested page myfunc method will be executed.
----------------------------
 
In case you are not bound to using $.getJSON you can use other methods provided by jQuery which also supports the onError calls.
 
It's important to note that make of the shortcut Ajax calls (such as post()) do not include error handling by default. This technique will allow you to handle errors for any such call.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

saini arun
Software Developer (Senior)
India India
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130516.1 | Last Updated 25 Jun 2010
Article Copyright 2010 by saini arun
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid