Thiwanka Thiwanka - 4 months ago 9
Ajax Question

How to get more details regarding jquery ajax error?

This is my sample ajax code.

$.ajax({
type: 'POST',
url: validateAjaxURL,
success: function (data) {
var returnData = data;
if (returnData.match("^selectedUno-")) {
$('#new_caregiver_popup_div').dialog('close');
} else {
$("#new_caregiver_popup_div").html(data);
}
},
error: function() {
alert('Unable to contact server');
}
});


This is working fine. But if an error occurs it will only give the alert "Unable to contact server", so I want to get more details about the error such as what type of error, reason for the error etc. How can I do that?

Answer

I usually write the "error" function something like this:

function (jQXHR, textStatus, errorThrown) {
    alert("An error occurred whilst trying to contact the server: " + jQXHR.status + " " + textStatus + " " + errorThrown);
}

This is as per the documentation at http://api.jquery.com/jQuery.ajax/. There are 3 parameters you can read from in order to find out more. Depending on the nature of the error, sometimes it's more informative than others.

Also depending on your browser, looking in the console and the networking logging in the developer tools (F12 on most browsers) may also give you some clues.

Comments