JQuery / AJAX: how to determine when a host is offline

I have a jQuery script that polls my server for new data, but it needs to display an error message if for some reason it doesn’t work.

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 found that if you rename query.php, so it is not available, the error function starts and a message is displayed. However, if I take the web server offline, the error function does not start.

How can I adapt my code to detect when a node is unavailable?

+5
source share
1 answer

You should set a low timeout, and it should be noted that success will still be triggered, so you need to check to see if you have any data at this point to see if that time has expired.

.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.");
       }
});
+2
source

All Articles