0

I'm working on a web-tool. It is built with PHP, HTML and MySQL. My need is to check the reachability of the server every once in a while. So far, I've tried to sending a simple query through JQuery-Ajax function and if the query is received, display an OK message, otherwise show an ERROR message. This request is being sent every x amount of seconds. I would like to know if there is any better approach than mine or any other way to determine the server reachability. I would like the client side to know when the server is no longer active for whatever reason.

This is what I have so far:

Client Side

<!DOCTYPE html>
    <head>
        <script src="assets/js/jquery.js"></script>
        <link href="https://opensource.keycdn.com/fontawesome/4.7.0/font-awesome.min.css" rel="stylesheet">
    </head>
    <title>Check for MySQL availability</title>
    <body onload="checking()">
        <p style="display: inline;">MySQL</p>
        <!-- Simple circle colored as orange (determining), red (unavailable) and green (available) -->
        <p style="display: inline;" id="world"><i class="fa fa-circle" aria-hidden="true"></i></p>
    </body>
    <script>
        function checking(){
            var dataString = 'signum=some_string';
            $.ajax({
                type: "POST",
                url: "testsql.php",
                data: dataString,
                cache: true,
                timeout: 30000, //Timeout after 30 seconds
                beforeSend: function(){
                //Checking status... (orange)
                $("#world").html('<i class="fa fa-spinner fa-pulse fa-fw"></i>').css('color', 'orange');
                },
                error: function() {
                    //Show MySQL as unavailable (red)
                    $("#world").html('<i class="fa fa-circle" aria-hidden="true"></i>').css('color', 'red');
                },
                success: function(data){
                    if(!data){
                        console.err("Error!");
                        //MySQL is unavailable (red)
                        $("#world").html('<i class="fa fa-circle" aria-hidden="true"></i>').css('color', 'red');
                    }else if(data){
                        //MySQL is available (green)
                        console.log("MySQL available!");
                        $("#world").html('<i class="fa fa-circle" aria-hidden="true"></i>').css('color', 'green');
                        }else{
                        //MySQL is unavailable (red)
                        console.err("Error!");
                        $("#world").html('<i class="fa fa-circle" aria-hidden="true"></i>').css('color', 'red');
                    }
                }
            });
            //Send Ajax requests every 3 seconds
            var t = setTimeout(checking, 3000);
        }
    </script>
    </html>

Note: The solution provided on Is there any way to check reachability test of server in jQuery did not work for me

Community
  • 1
  • 1
  • 1
    The code looks ok I guess. You could expand it by checking the http status code to be more specific, so you can see if the issue is the internet connetion or the database itself etc. If you can use `websockets` or other `server push technology`, you don't have to do all this, and just have the server notify the client instead. But otherwise you're stuck with this kind of `polling`. – Shilly Mar 14 '17 at 17:01
  • Tried expanding by catching the errors jqXHR, textStatus, errorThrown on the error function, it but I guess with the fact that I get to know there is an error is enough to make my client aware. I'll investigate further on the websockets implementation, though. Thanks for the insight. – Luis Altúzar Mar 14 '17 at 20:24

1 Answers1

1

It might be a bit more efficient to use an image (assuming that your server successfully sending an image indicates that it is up):

function checkStatus(imgUrl) {
    return new Promise(function(resolve, reject) {
        var img = new Image();
        img.src = imgUrl;
        img.onload = resolve;
        img.onerror = reject;
    });
}

var imageUrl = 'https://cdn.sstatic.net/Sites/stackoverflow/img/sprites.svg?v=d689de80c4e2';
var UPTIME_INTERVAL = 3000;

setInterval(function() {
    checkStatus(imageUrl)
       .then(function(success) { console.log('success') })
       .catch(function(err) { console.log('error') })
}, UPTIME_INTERVAL);

Edit: A very small image would be ideal in this scenario

Rob M.
  • 35,491
  • 6
  • 51
  • 50
  • Thanks! I'll try this and see how it goes; had not thought about showing images rather than strings or simple variable values. – Luis Altúzar Mar 14 '17 at 18:10
  • https://github.com/mdn/js-examples/blob/master/promises-test/index.html found this resource, in any case someone wants to take a look into the new Promise function. Very useful for this case! – Luis Altúzar Mar 14 '17 at 20:53