0

I'm very new to Javascript and I have a button that need to be constantly checked against whether a server is active or not.

I'm using the Play framework based in Java. I already have a class ServerStatus that returns whether a service is healthy or not but I am not sure how to link this into my page which contains the button.

Basically, what I want is that if the server goes down then I want the button disabled so that the user cannot use it while the server is unavailable.

I looked a bit at Websockets and that looks really complex. I wasn't sure if there is a simpler way.

EDIT

Using Websockets: I had a read around and it seems I need to use the onmessage event. I found some sample code but I am not sure how to put this into my (document).ready function.

Below I have some code:

$(document).ready(function(){
  var WS = window['MozWebSocket'] ? MozWebSocket : WebSocket;
  var chatSocket = new WS("routes");//This does not seem to accept any @routes
  var lastState = 'unknown';
  chatSocket.onmessage = function(e){
  var server_message = e.data;
  //do something here about enabling and disabling
  console.log(server_message);
  }
});

function disable()
{
  //disable all buttons
}
function enable()
{
  //enable all buttons
}

I am lost as to how to add the websocket here.

nbz
  • 3,806
  • 3
  • 28
  • 56
  • Can either use Websockets, Long Polling, SSE (Server side events), etc. Do a bit of research on these technologies to see what would work best for you. – proulxs Sep 29 '14 at 17:34
  • In your above code the variables fall out of scope at the end of the ready function. So it is possible this doesn't execute correctly. I would suggest moving the var declaration outside the function. EXAMPLE: var WS = null. And then inside document ready function you can drop the var before initialization. I am not too familiar with web sockets, but from a JS view, I would at least move the var declaration up a level. –  Sep 30 '14 at 14:43

1 Answers1

1

I am borrowing heavy from this similar question and answer

The basic code is here:

var isNotWorking = false;

var myFunc = function(){

$.ajax({url: "YOUR_URL_HERE",
        type: "HEAD",
        timeout:1000,
        statusCode: {
            200: function (response) {
                //alert('Working!');
                isNotWorking =false;
            },
            400: function (response) {
                //alert('Not working!');
                isNotWorking = true;
            },
            0: function (response) {
                //alert('Not working!');
                isNotWorking = true;
            }              
        }
 });

    $('#mybutton').prop('disabled', isNotWorking);

    doSetTimeOut();
}

var doSetTimeOut = function(){

    setTimeout(function(){

        myFunc();


    }, 1000);

}


doSetTimeOut();

See a working JS fiddle here

Community
  • 1
  • 1