Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript/dashcode: check for internet connection

i'm developing a widget that is fetching data from the internet via ajax and i want to provide a error message, if the widget cannot connect to the server. i'm doing the request with jquery's ajax object which provides a error callback function, but it's not called when there is no internet connection, only if the request is made but fails for other reasons.

now how can i check if the computer is connected to the internet?

like image 704
Patrick Oscity Avatar asked Sep 14 '26 12:09

Patrick Oscity


2 Answers

UPDATE: Since you are creating a Dashboard widget, I ran a number of tests.

I found that the $.ajax call actually triggered an error when there was no internet connection. So I went about creating a XMLHTTPRequest object manually with great success. If you need JSON parsing, I suggest also including the json2.js parser.

Things I did to make this work:

  1. In Widget Attributes in Dashcode I clicked "Allow Network Access" (If you aren't using Dashcode, check the docs for the proper plist setting to turn this on)
  2. I used the following code:
var xhr = new XMLHttpRequest();
xhr.addEventListener('readystatechange', state_change, true);
xhr.open("GET", url, true);
xhr.send(null);

function state_change(){
   if(xhr.readyState == 4){
        if(xhr.status == 200){
          console.log('worked'); // Only works if running in Dashcode
          // use xhr.responseText or JSON.parse(xhr.responseText)
        } else if(xhr.status == 0) {
          console.log('no internet'); // Only works if running in Dashcode
        } else {
          // Some other error
        } 
   }
}

/End Update

I answered this by editing my answer to your original question since you asked it in the comments. After commenting I saw you posted this question.

To summarize, add the timeout parameter to your $.ajax call and set it to a low number (like 5000 milliseconds). Your error function will be called after the request times out.

like image 178
Doug Neiner Avatar answered Sep 17 '26 01:09

Doug Neiner


in your error function, the second argument is status, check to see if that == "timeout", if it does, you couldn't reach the webservice (or whatever you're connecting to), regardless of whether you have internet access or not, I'm assuming that's what you care about.

$.ajax({
   /* your other params here*/
   error: function (req, status, error) {
      if(status == "timeout") alert("fail!");
   },
   timeout: 2000 //2 seconds
});

See the sections on timeout and error here.

like image 36
Ben Lesh Avatar answered Sep 17 '26 02:09

Ben Lesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!