ssh2ksh
ssh2ksh

Reputation: 489

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 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?

Upvotes: 5

Views: 4020

Answers (1)

Sarke
Sarke

Reputation: 3235

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

Upvotes: 2

Related Questions