Test Internet Connection using AJAX






2.12/5 (8 votes)
Sometimes when the internet connections is unstable, we have to check again and again if the connection is active? This script does this task for us.
Introduction
Sometimes when the internet connections is unstable, we have to check again and again if the connection is active? This script does this task for us.
This script checks the connectivity of internet connection every 20 seconds. If internet is not connected, it displays a message that internet is not connected. And, when the system is connected to internet, it shows the message that "Internet is connected."
Using the code
In this script, we send a request to a web page using the JavaScript object XmlhttpRequest
. If the request is unsuccessful, it will try to reconnect again after 20 seconds. In the case of success, it shows a message that "Internet is connected".
var xmlhttp
function ConnectToNet(url)
{
xmlhttp=null;
try {
netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
} catch (e) {
//For IE it comes here.
//alert("Permission UniversalBrowserRead denied.");
}
// code for Mozilla, etc.
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest()
}
// code for IE
else if (window.ActiveXObject){
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
}
if (xmlhttp!=null){
xmlhttp.onreadystatechange=state_Change
xmlhttp.open("GET",url,true)
xmlhttp.send(null)
}
else{
alert("Your browser does not support XMLHTTP.")
}
}
function state_Change()
{
// if xmlhttp shows "loaded"
if (xmlhttp.readyState==4){
try{
// if "OK"
if (xmlhttp.status==200){
var objDiv = document.getElementById('div1');
objDiv.innerHTML = "<font color=blue>Internet is connected.</font>";
alert("Internet is Connected.");
return;
}
else{
alert("Problem retrieving XML data")
}
} catch(err){
var objDiv = document.getElementById('div1');
objDiv.innerHTML += "<font color=red>Internet is not connected.<br/></font>";
setTimeout("ConnectToNet('http://www.google.com')",20000);
}
}
}