I have a jQuery script that polls my server for new data, but it needs to display an error message if it fails for any reason.
Here is my AJAX request:
$.ajax({
url: "query.php", // This just runs some MySQL queries and echos the results
cache: false,
error: function() {
$(".status").text("Server is offline.");
},
success: function(html) {
// Everything went fine, append query results to div
}
});
I've found that if rename query.php so it is unreachable, the error function triggers and the message is displayed. However, if I take the web server offline the error function doesn't trigger.
How can I adapt my code to detect when the host is unreachable?
You should set a low timeout, and the thing to note is that the success will still be called so you have to check if you have any data at that point to know if it timed out or not.
.ajax({
url: "query.php", // This just runs some MySQL queries and echos the results
cache: false,
timeout: 4000, // 4 seconds
error: function() {
$(".status").text("Unable to retrieve data.");
},
success: function(html) {
if (html) {
// Everything went fine, append query results to div
}
else {
$(".status").text("Server is offline.");
}
});
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