Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 639
TTCG Avatar asked May 14 '10 12:05

TTCG


People also ask

How does error handle response in AJAX?

When there is an AJAX error response or the AJAX request times out, you'll want to log as much information as you have, including the error message that jQuery gives you, the url and the request data. $. ajax(url, { "data": requestData, "type": "POST", "timeout": 5000 }) .

How do I know if AJAX request is successful?

$. ajax({ url: "page. php", data: stuff, success: function(response){ console. log("success"); } });


1 Answers

Since jQuery 1.5 you can use the deferred 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");   } }); 
like image 153
choise Avatar answered Sep 26 '22 02:09

choise