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?
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 }) .
$. ajax({ url: "page. php", data: stuff, success: function(response){ console. log("success"); } });
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"); } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With