How to alert the user when there's no internet connection

user1315906 picture user1315906 · May 7, 2012 · Viewed 12.4k times · Source

I need to alert the user with the following conditions;

  1. Request timed out
  2. No internet connection
  3. Unable to reach the server

Here's the code; How to capture the following conditions when occurred and alert the user ?

failure: function (response) {
    var text = response.responseText;
    console.log("FAILED");
},success: function (response) {
    var text = response.responseText;
    console.log("SUCCESS");
}

I tried the following code to check if the internet is reachable, but it didn't work

var networkState = navigator.network.connection.type
    alert(states[networkState]);
    if (networkState == Connection.NONE){
        alert('No internet ');
    };

UPDATE **

I added the following in my index.html, but, when i disable WIFI, i don't see the alert popping.

<script>
function onDeviceReady() {
    document.addEventListener("offline", function() {
        alert("No internet connection");
    }, false);
}
</script>

Answer

Simon MacDonald picture Simon MacDonald · May 7, 2012

The best thing to do is to listen to the "offline" event. When you get the offline event you can warn your user and take whatever steps necessary to save data, etc.

For instance, your "deviceready" callback:

document.addEventListener("offline", function() {
    alert("No internet connection");
}, false);

This code should work for most all versions of PhoneGap. It's been in since at least the 1.0 release.