I would like to catch the error and show the appropriate message if the Ajax request fails.
My code is like the following, but I could not manage to catch the failing Ajax request.
function getAjaxData(id)
{
$.post("status.ajax.php", {deviceId : id}, function(data){
var tab1;
if (data.length>0) {
tab1 = data;
}
else {
tab1 = "Error in Ajax";
}
return tab1;
});
}
I found out that, "Error in Ajax" is never executed when the Ajax request failed.
How do I handle the Ajax error and show the appropriate message if it fails?
Since jQuery 1.5 you can use the deferred objects mechanism:
Another way is using
.ajax
:jQuery 1.5 added deferred objects that handle this nicely. Simply call
$.post
and attach any handlers you'd like after the call. Deferred objects even allow you to attach multiple success and error handlers.Example:
Prior to jQuery 1.8, the function
done
was calledsuccess
andfail
was callederror
.A simple way is to implement ajaxError:
For example:
I would suggest reading the ajaxError documentation. It does more than the simple use-case demonstrated above - mainly its callback accepts a number of parameters:
I fixed this problem by declaring
datatype: 'json'
in my jQuery ajax call.