Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery/AJAX: How to determine when a host is offline

Tags:

jquery

ajax

php

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?

like image 248
ssh2ksh Avatar asked Nov 03 '22 22:11

ssh2ksh


1 Answers

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.");
       }
});
like image 82
Sarke Avatar answered Nov 15 '22 05:11

Sarke