Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
7
rated 0 times [  12] [ 5]  / answers: 1 / hits: 53267  / 14 Years ago, mon, march 7, 2011, 12:00:00

What's the fastest way to check if my server is online via JavaScript?



I've tried the following AJAX:



function isonline() {
var uri = 'MYURL'
var xhr = new XMLHttpRequest();
xhr.open(GET,uri,false);
xhr.send(null);
if(xhr.status == 200) {
//is online
return xhr.responseText;
}
else {
//is offline
return null;
}
}


The problem is, it never returns if the server is offline. How can I set a timeout so that if it isn't returning after a certain amount of time, I can assume it is offline?


More From » javascript

 Answers
44

XMLHttpRequest does not work cross-domain. Instead, I'd load a tiny <img> that you expect to come back quickly and watch the onload event:



function checkServerStatus()
{
setServerStatus(unknown);
var img = document.body.appendChild(document.createElement(img));
img.onload = function()
{
setServerStatus(online);
};
img.onerror = function()
{
setServerStatus(offline);
};
img.src = http://myserver.com/ping.gif;
}


Edit: Cleaning up my answer. An XMLHttpRequest solution is possible on the same domain, but if you just want to test to see if the server is online, the img load solution is simplest. There's no need to mess with timeouts. If you want to make the code look like it's synchronous, here's some syntactic sugar for you:



function ifServerOnline(ifOnline, ifOffline)
{
var img = document.body.appendChild(document.createElement(img));
img.onload = function()
{
ifOnline && ifOnline.constructor == Function && ifOnline();
};
img.onerror = function()
{
ifOffline && ifOffline.constructor == Function && ifOffline();
};
img.src = http://myserver.com/ping.gif;
}

ifServerOnline(function()
{
// server online code here
},
function ()
{
// server offline code here
});

[#93388] Saturday, March 5, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
alora

Total Points: 284
Total Questions: 99
Total Answers: 92

Location: Singapore
Member since Sat, Jul 25, 2020
4 Years ago
;