Saturday, January 22, 2011

Global Error handling in Jquery Ajax requests

JQuery provides very easy way to give asynchronous call to server using $.get , $.post and $.ajax methods. You can see the details of this methods on the JQuery API document (http://api.jquery.com/)

I will not give in details of the these methods as its a pretty easy to learn and use these APIs from the above site. I am going to explain How to do the error handling for Ajax call. Once the ajax call is made using one of the above method to the server, server process the request and send the result back to the browser. But what if error occurs? In this case user should be notified with the proper message and proper information should be logged at server so that developer can solve the problem using logs.

In case of $.ajax function you will find the error function :
error(XMLHttpRequest, textStatus, errorThrown)

which gets called when the request is failed. But if you are giving multiple ajax calls then you need to write this error function multiple time and what if you forgot to write and it and handle it care fully...leads to error prone programming and code becomes hard to maintain.For other functions like $.get and $.post there is no error function provided.

So best way to handle the error in case of ajax calls is to handle them globally. Write function as follows:

$(window).ready(function () {
$.ajaxSetup({
error: function (xhr, textStatus, errorThrown) {

alert(xhr.statusText);
showMessage(xhr.statusText);
}
});
}
);

function showMessage(msg) {
$("#message").text(msg);
$("#message").dialog({ height: 75, position: 'top', resizable: false, zIndex: 4000});

So in first function, It setup the ajax settings for all subsequent calls.Hence if there is any error in $.get, $.post or $.ajax calls it will be handled in first function. This function handles the error and show the statusText to the user. More about the ajaxSetup can be seen in the above Jquery API document.
}

1 comment:

Anonymous said...

Often remarks honestly will likely be challenging to trust but there’s
a great deal of appropriate as well as beneficial recommendations the following.
Folks who write-up this info can absolutely be thanked.
Also visit my web-site : Ajax examples