TTCG TTCG - 4 months ago 12
Ajax Question

how to catch 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 failure 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 to handle the ajax error and show the appropriate message if it fails? Thanks very much.

Answer

since jQuery 1.5 you can use deffered objects mechanism

$.post('some.php', {name: 'John'})
    .done(function(msg){  })
    .fail(function(xhr, status, error) {
        // error handling
    });

another way is using .ajax

$.ajax({
  type: "POST",
  url: "some.php",
  data: "name=John&location=Boston",
  success: function(msg){
        alert( "Data Saved: " + msg );
  },
  error: function(XMLHttpRequest, textStatus, errorThrown) {
     alert("some error");
  }
});
Comments