How do I catch an Ajax query post error?

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?

8 Answers
8

Leave a Comment