Link to home
Start Free TrialLog in
Avatar of xenia27
xenia27Flag for Taiwan, Province of China

asked on

Internet Connection Fail

I wonder if I can know the internet connection is failed by any way???  I have a program that requires and uses Google map API so I need the internet access.  However, my users are not always having internet access...so I wonder whether is there any way that I can know the internet access is available or not??
Avatar of vinodsnair2001
vinodsnair2001
Flag of India image

Avatar of Gurvinder Pal Singh
It should be simple
Fire an Ajax request for that URL, see the reference http://www.xul.fr/en-xml-ajax.html#ajax-xmlhttprequest

If the status is 200, then the connection is ok, else it is not.



Avatar of xenia27

ASKER

I don't know what's wrong...but I cannot know the status...here is my code...there is some error when I try to show xhr.status...
function init_startup(){
  var xhr; 
  try {  xhr = new ActiveXObject('Msxml2.XMLHTTP');   }
  catch (e) 
  {
    try {   xhr = new ActiveXObject('Microsoft.XMLHTTP');    }
    catch (e2) 
    {
      try {  xhr = new XMLHttpRequest();     }
      catch (e3) {  xhr = false;   }
    }
  }

  alert(xhr);
			
  xhr.onreadystatechange  = function()
  { 
    if(xhr.readyState  == 4)
    {
      if(xhr.status  == 200) 
        alert("status == 0");
      else 
        alert("else");
    }
  }; 

  alert(xhr.status);

} // end of init_startup

Open in new window

Please try the following code.

function ConnectToNet(url)
{
    if (window.XMLHttpRequest)
    {
        xmlhttp=new XMLHttpRequest()
    }
    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.")
    }
}


unction state_Change()
{
    if (xmlhttp.readyState==4)
    {
        try
        {
            if (xmlhttp.status==200)
            {    
                 alert("connection ok");
            }
            else
            {
                 alert("connection not ok");
            }
        } 
        catch(err)
        {
            alert("connection not ok");
        }
    }
}

Open in new window

Avatar of xenia27

ASKER

I got some error on this line...xmlhttp.open("GET",url,true);....something like access deny...
I try to the url is "http://www.google.com"...what should I do???
Not sure, why you are facing this issue.
the same code is working fine on my machine

try this
http://forums.devshed.com/javascript-development-115/ajax-problem-access-is-denied-452579.html

I know why, the JavaScript standard has same-origin policy that only allows JavaScript scripts to interact only with the scripts' primary host.

Unless your script is somehow embedded inside a google.com's page, you may not access any Ajax-statechange properties of any google.com's web page.

Some Web Browsers doesn't implement this policy strictly and some does.

I've just tested these codes and Mozilla Firefox allows you to get all of the google.com xmlhttp object's properties in your own site while Internet Explorer will issue a "Permission denied" error!

However, if you try to get all of xmlhttp object's properties of your own site's pages, all of the browsers will allow you!

I may return with further findings...
Meanwhile, you can always test whether the user can even fetch a new, uncached page (by appending random numbers to the end of the filename) from your own site with the same technique... if they can't fetch a new page from your own site, then they've been disconnected from the internet.

Here's a simple Ajax code you can use:

function isOnline(){
var xmlHttp="XMLHttpRequest" in window?(new XMLHttpRequest()):("ActiveXObject" in window?(new ActiveXObject("Microsoft.XMLHttp")):null); // The XMLHttp Object

 // The local test page, can even be a blank page!
// You can also do a relative URL:
// var testURL="/yourpage.html";
var testURL="http://www.yoursite.com/yourpage.html";
testURL+="?"+Math.random(); // Append random number so that the browser always tries to get a fresh version of the page

   xmlHttp.onreadystatechange=
   function(){
      if (xmlHttp.readyState=="4" || xmlHttp.readyState=="complete"){
         if (xmlHttp.status==200 || xmlHttp.statusText=="OK"){
         alert("Currently ONline."); // Connection successful
         }
         else{
         alert("Currently OFFline."); // Connection failed. 2 reasons: user is offline -OR- the page cannot be fetched (server error, page doesn't exist, forbidden, etc.)
         }
      }
   };

xmlHttp.open("GET",testURL,true); // Open an asynchronous "GET" request for the testURL
xmlHttp.send(null); // Send nothing since it's a "GET" request
}
ASKER CERTIFIED SOLUTION
Avatar of hsq91
hsq91
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of xenia27

ASKER

hsq91,

I tried your function...and even I am online and I had a return value said "Currently OFFline"...what's wrong??  I have "404 not found" error...but it should be found...
My testURL is "/www.google.com"...any idea?
You're testing a relative, non-existent URL in your page, not the actual http://www.google.com/ !
As I've said JavaScript doesn't allow you to actually access any files that's outside of your script's current URL. Not all browsers will allow you to use http://www.google.com/ for testing unless your script is hosted by google.com.

Once again, simply replace the testURL to an actual page in your site. You can simply use the index page of your home page:

For example, if your site is http://www.mysite.com/
and if your script is placed somewhere inside it, such as:
http://www.mysite.com/scripts/myscript.js

You can simply set your testURL equals to "/" --or even more specific "/index.php" or "/index.html" , depending on what you name your site's index page-- to use the parent index as your testURL.


Avatar of xenia27

ASKER

Now I see what's wrong...
But is there anyway that I can make sure the connection to google is open??
Well, consider the fact that google usually has multiple backup servers, so it's likely to be 100% always open.

For simplicity, whenever the user can get a fresh, newest version of your site's Web Page, it is assumed that user, using normal browsing and internet security/firewall settings, should be able to access google.com!

Other than that, I do not yet see an apparent, simple, JavaScript-only way to detect whether google.com is online.

You could, however, try to use Server-side Programming languages, such as PHP, and use its file_get_contents() built-in function:

<?php /* If your site/server supports the PHP programming language, this should run */
// example-google-availability-test.php
$aGooglePage="/"; // URL relative to google.com

$aGooglePage="http://www.google.com".(strpos($aGooglePage,"/")===0?$aGooglePage:"/$aGooglePage"); // Make the relative URL absolute

   // If your server allows the use of file_get_contents() to get data from external sites, this should run
   if (!@($googleResponse=@file_get_contents($aGooglePage))){ // If failed to get the contents of $aGooglePage, send a 404 - Not Found Error that can even be used by my previous JavaScript
   header("HTTP/1.0 404 Not Found");
   exit; // Exit the program
   }
echo $googleResponse; // Otherwise, give the contents of $aGooglePage to prove a fetch-file success
?>
Simply store the PHP code above (beginning with <?php and ending with ?>) in a blank file named something like example-google-availability-test.php located inside your site's root folder, "/"

Using the JavaScript code I've provided, you would simply replace testURL to that PHP page's URL:

testURL="/example-google-availability-test.php"; // This URL/page will tell the JavaScript what's the response from the tested google.com page
Avatar of xenia27

ASKER

Thanks for your help~  Finally, my problem is solved!