?
Solved

Internet Connection Fail

Posted on 2009-12-20
15
Medium Priority
?
396 Views
Last Modified: 2012-05-08
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??
0
Comment
Question by:xenia27
  • 6
  • 5
  • 3
  • +1
15 Comments
 
LVL 2

Expert Comment

by:vinodsnair2001
ID: 26094173
0
 
LVL 40

Expert Comment

by:Gurvinder Pal Singh
ID: 26094176
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.



0
 

Author Comment

by:xenia27
ID: 26101955
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

0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 40

Expert Comment

by:Gurvinder Pal Singh
ID: 26102089
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

0
 

Author Comment

by:xenia27
ID: 26102313
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???
0
 
LVL 40

Expert Comment

by:Gurvinder Pal Singh
ID: 26102476
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

0
 
LVL 3

Expert Comment

by:hsq91
ID: 26114350
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...
0
 
LVL 3

Expert Comment

by:hsq91
ID: 26114475
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
}
0
 
LVL 3

Accepted Solution

by:
hsq91 earned 2000 total points
ID: 26114712
Here's the more robust Ajax code you can use for detecting the user's current internet-connectivity state. Tested to work in the latest IE, FF, GChrome, Safari, and Opera browsers without the need to reload a page:

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="/index.php";
testURL+="?"+Math.random(); // Append random number so that the browser always tries to get a fresh version of the page

   xmlHttp.onreadystatechange=
   function(){
   try{ // If something doesn't work right, even when the test page is within the same domain, then it's likely that the user is truly offline.
      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.)
         }
      }
   }
   catch(er){ // For sure, the user is fully OFFline
   alert("Currently OFFline.\nError occurred while trying to establish any connection:\n\n"+er.name+": "+er.message); // Connection failed with errors
   }
   };

xmlHttp.open("GET",testURL,true); // Open an asynchronous "GET" request for the testURL
xmlHttp.send(null); // Send nothing since it's a "GET" request
}

You can then use a test button and try disconnecting/re-connecting your Internet connection for testing, as I've done:
<input type="button" onclick="isOnline();" value="Am I online?" />
0
 

Author Comment

by:xenia27
ID: 26129315
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?
0
 
LVL 3

Expert Comment

by:hsq91
ID: 26129358
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.


0
 

Author Comment

by:xenia27
ID: 26129365
Now I see what's wrong...
But is there anyway that I can make sure the connection to google is open??
0
 
LVL 3

Expert Comment

by:hsq91
ID: 26129412
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
?>
0
 
LVL 3

Expert Comment

by:hsq91
ID: 26129438
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
0
 

Author Closing Comment

by:xenia27
ID: 31668428
Thanks for your help~  Finally, my problem is solved!
0

Featured Post

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
This article discusses how to implement server side field validation and display customized error messages to the client.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses
Course of the Month16 days, 6 hours left to enroll

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question