JQuery ajax error function

ajaxjquery

I have an ajax call passing data to a page which then returns a value.

I have retrieved the successful call from the page but i have coded it so that it raises an error in the asp. How do i retrieve that error from the jquery?

For example:

cache: false,
url: "addInterview_Code.asp",
type: "POST",
datatype: "text",
data: strData,
success: function (html) {
    alert('successful : ' + html);
    $("#result").html("Successful");
},
error: function (error) {
    **alert('error; ' + eval(error));**
}

It's the error bit that I don't understand. In the function what parameter do I need to put, so that I can then use the error message that I raised in the server.

Best Answer

The required parameters in an Ajax error function are jqXHR, exception and you can use it like below:

$.ajax({
    url: 'some_unknown_page.html',
    success: function (response) {
        $('#post').html(response.responseText);
    },
    error: function (jqXHR, exception) {
        var msg = '';
        if (jqXHR.status === 0) {
            msg = 'Not connect.\n Verify Network.';
        } else if (jqXHR.status == 404) {
            msg = 'Requested page not found. [404]';
        } else if (jqXHR.status == 500) {
            msg = 'Internal Server Error [500].';
        } else if (exception === 'parsererror') {
            msg = 'Requested JSON parse failed.';
        } else if (exception === 'timeout') {
            msg = 'Time out error.';
        } else if (exception === 'abort') {
            msg = 'Ajax request aborted.';
        } else {
            msg = 'Uncaught Error.\n' + jqXHR.responseText;
        }
        $('#post').html(msg);
    },
});

DEMO FIDDLE


Parameters

jqXHR:

Its actually an error object which is looks like this

Ajax error jqXHR object

You can also view this in your own browser console, by using console.log inside the error function like:

error: function (jqXHR, exception) {
    console.log(jqXHR);
    // Your error handling logic here..
}

We are using the status property from this object to get the error code, like if we get status = 404 this means that requested page could not be found. It doesn't exists at all. Based on that status code we can redirect users to login page or whatever our business logic requires.

exception:

This is string variable which shows the exception type. So, if we are getting 404 error, exception text would be simply 'error'. Similarly, we might get 'timeout', 'abort' as other exception texts.


Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

So, in case you are using jQuery 1.8 or above we will need to update the success and error function logic like:-

// Assign handlers immediately after making the request,
// and remember the jqXHR object for this request
var jqxhr = $.ajax("some_unknown_page.html")
    .done(function (response) {
        // success logic here
        $('#post').html(response.responseText);
    })
    .fail(function (jqXHR, exception) {
        // Our error logic here
        var msg = '';
        if (jqXHR.status === 0) {
            msg = 'Not connect.\n Verify Network.';
        } else if (jqXHR.status == 404) {
            msg = 'Requested page not found. [404]';
        } else if (jqXHR.status == 500) {
            msg = 'Internal Server Error [500].';
        } else if (exception === 'parsererror') {
            msg = 'Requested JSON parse failed.';
        } else if (exception === 'timeout') {
            msg = 'Time out error.';
        } else if (exception === 'abort') {
            msg = 'Ajax request aborted.';
        } else {
            msg = 'Uncaught Error.\n' + jqXHR.responseText;
        }
        $('#post').html(msg);
    })
    .always(function () {
        alert("complete");
    });

Hope it helps!