Friday, October 12, 2012

jQuery Ajax Error Handling Example

jQuery provides an error handler event ajaxError to handle errors which occur while making Ajax requests using jQuery. We can bind the ajaxError event to an error handler method and use the method to display the errors in an user friendly way.

In this post we shall see on how to use the ajaxError event to display the exception details.
We will try to call a HTML page which does not exist in the server and see on how the error is handled.

Add the following code to a page, and click on the Error Handler button.

<html xmlns="" >
<head runat="server">
    <title>Ajax Handlers</title>
<script type="text/javascript" src="JavaScript/jquery-1.7.2.js"></script>
        $(document).ready(function() {
            // Get HTML Response data from the Server
            $('#btnErrorHandler').click(function(event) {
                    url: "UnknownPage.html",
                    cache: false,
                    dataType: "html",
                    success: function(result) {
                // Error Handler
                $("#divErrorLog").ajaxError(function(objEvent, objHttp, objSettings, jsExe) {
                    var errMsg;
                    errMsg += "Request URL: " + objSettings.url + "</br>";
                    errMsg += "XMLHttpRequest Status: " + objHttp.status + "</br>";
                    errMsg += "Error Message: " + objHttp.statusText + "</br>";
                    errMsg += "JavaScript Err Msg: " + jsExe + "</br>";
    <form id="AjaxHandlers" runat="server">
        <table border="1">
            <tr valign="middle">
                        Text="Error Handler" />
                <td align="center">
                    <br /><div id="divHTML"></div> 
            <tr valign="middle">
                    Error Log:
                <td align="left">
                    <br />
                    <div id="divErrorLog"

On clicking the button jQuery tries to get the data from a HTML page
UnknownPage.html, which does not exist in the server, this will trigger the ajaxError event, the error handling function handles the error and displays the error message in the divErrorLog DIV.

Notice that the ajaxError are common and will be called for all the Ajax requests in the page, we will have to identify and map the error with the request using the settings parameters of the ajaxError event.

Related Post

Search Flipkart Products:

No comments: