Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>
like image 303
user1315906 Avatar asked May 07 '12 12:05

user1315906


People also ask

How do I say no internet connection?

The easiest way to let people know you're having internet issues is to say you have a “bad (internet) connection.” It looks like I'm having a bad connection today. Could you say that again, please? Sorry, I think the connection is bad.

How do I get an alert when my internet is down?

Pay your ISP for a fixed IP, then either pay an organisation such as SiteConfidence to monitor / ping your router, and alert you when unreachable. Alternatively install something like SmokePing or Cacti on an external machine or virtual machine and configure it to ping your router, sending an alert if it goes down.

What happens when it says connected without internet?

If all your devices get no internet connection, yet your WiFi indicator is still on, the most obvious answer is that your internet provider has an outage. Before you start rebooting and shuffling wires around, it's always a good idea to check this first.


1 Answers

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.

like image 66
Simon MacDonald Avatar answered Sep 30 '22 03:09

Simon MacDonald