12

I am trying to check for the internet connection by sending a GET request to the server. I am a beginner in jquery and javascript. I am not using navigator.onLine for my code as it works differently in different browsers. This is my code so far:

var check_connectivity={
        is_internet_connected : function(){
            var dfd = new $.Deferred();
            $.get("/app/check_connectivity/")
            .done(function(resp){
                return dfd.resolve();
            })
            .fail(function(resp){
                return dfd.reject(resp);
            })
            return dfd.promise();
        },
}

I call this code in different file as:

if(!this.internet_connected())
        {
            console.log("internet not connected");
            //Perform actions
        }
internet_connected : function(){
        return check_connectivity.is_internet_connected();
},

The is_internet_connected() function returns a deferred object whereas I just need an answer in true/false. Can anybody tell me about how to achieve this?

Gaurav
  • 1,005
  • 3
  • 14
  • 33

8 Answers8

11

$.get() returns a jqXHR object, which is promise compatible - therefore no need to create your own $.Deferred.

var check_connectivity = {
    ...
    is_internet_connected: function() {
        return $.get({
            url: "/app/check_connectivity/",
            dataType: 'text',
            cache: false
        });
    },
    ...
};

Then :

check_connectivity.is_internet_connected().done(function() {
    //The resource is accessible - you are **probably** online.
}).fail(function(jqXHR, textStatus, errorThrown) {
    //Something went wrong. Test textStatus/errorThrown to find out what. You may be offline.
});

As you can see, it's not possible to be definitive about whether you are online or offline. All javascript/jQuery knows is whether a resource was successfully accessed or not.

In general, it is more useful to know whether a resource was successfully accessed (and that the response was cool) than to know about your online status per se. Every ajax call can (and should) have its own .done() and .fail() branches, allowing appropriate action to be taken whatever the outcome of the request.

Beetroot-Beetroot
  • 18,022
  • 3
  • 37
  • 44
6

Do you mean to check the internet connection if it's connected?

If so, try this:

$.ajax({
    url: "url.php",
    timeout: 10000,
    error: function(jqXHR) { 
        if(jqXHR.status==0) {
            alert(" fail to connect, please check your connection settings");
        }
    },
    success: function() {
        alert(" your connection is alright!");
    }
});
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Stanley Amos
  • 222
  • 2
  • 8
  • Alert won't work for me. I have to return a true or false value. – Gaurav Nov 18 '13 at 10:20
  • Useless way to check connection! why would anyone check net connection, if they know they are connected. – Vikrant Feb 23 '15 at 12:40
  • 3
    It is possible that connection may be dropped for a certain amount of time, so it would be good to check if that is the case. – EpicJoker Jun 23 '16 at 10:03
4

100% Working:

function checkconnection() {
    var status = navigator.onLine;
    if (status) {
        alert('Internet connected !!');
    } else {
        alert('No internet Connection !!');
    }
}
Fezal halai
  • 756
  • 7
  • 14
4

This piece of code will continue monitoring internet connection click bellow "Run code snippet" button and see it in action.

function checkInternetConnection(){
        var status = navigator.onLine;
        if (status) {
            console.log('Internet Available !!');
        } else {
            console.log('No internet Available !!');
        }  
        setTimeout(function() {
            checkInternetConnection();
        }, 1000);
      }

//calling above function
checkInternetConnection();
Muhammad Tahir
  • 2,351
  • 29
  • 25
  • 3
    OP says they don't want to use `navigator.onLine`. Also a note: `"online" does not always mean connection to the internet, it can also just mean connection to some network.` which means being connected to a router even when the router has no internet will mean that online is true – zanderwar Jun 07 '20 at 23:55
  • From Mozilla: ```In Chrome and Safari, if the browser is not able to connect to a local area network (LAN) or a router, it is offline; all other conditions return true. So while you can assume that the browser is offline when it returns a false value, you cannot assume that a true value necessarily means that the browser can access the internet.``` This is not at safe to use for checking "internet" connection in a browser. it's value reflects ONLY the LAN and we can't assume this means connection to the web. Ref: https://developer.mozilla.org/en-US/docs/Web/API/NavigatorOnLine/onLine – Donovan Oct 03 '20 at 18:02
1
try this 
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
 if (! window.jQuery) {
 alert('No internet Connection !!');
  }
 else {
 // internet connected
 }

Jquery Plugin for Detecting Internet Connection

Community
  • 1
  • 1
Mahmoude Elghandour
  • 2,921
  • 1
  • 22
  • 27
  • 2
    I am caching the jquery library in user's local machine so that he doesn't need to download it everytime he opens the website. So this idea won't work for me. – Gaurav Nov 18 '13 at 09:56
  • this check will work only the first time you loaded the website, not on every AJAX request – Ricky Levi Apr 11 '19 at 08:47
1

It's working fine for me.

   <div id="status"></div>


    <script>
     window.addEventListener("offline", (event) => {
      const statusDisplay = document.getElementById("status");
      statusDisplay.textContent = "OFFline";
    });

    window.addEventListener("online", (event) => {
      const statusDisplay = document.getElementById("status");
      statusDisplay.textContent = "Online";
    });
  </script>
lincolndu
  • 93
  • 1
  • 8
0

you cannot get simple true or false in return, give them a callback handler

function is_internet_connected(callbackhandler)
{
$.get({
  url: "/app/check_connectivity/",
  success: function(){
     callbackhandler(true);
  },
  error: function(){
     callbackhandler(false);
  },
  dataType: 'text'
});
}
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
  • I think deferred objects were created so as to avoid callback handler. In any case, my problem can't be solved using callback handler. – Gaurav Nov 18 '13 at 09:54
0

I just use the navigator onLine property, according to W3C http://www.w3schools.com/jsref/prop_nav_online.asp

BUT navigator only tells us if the browser has internet capability (connected to router, 3G or such). So if this returns false you are probably offline but if it returns true you can still be offline if the network is down or really slow. This is the time to check for an XHR request.

setInterval(setOnlineStatus(navigator.onLine), 10000);

function setOnlineStatus(online)
{
    if (online) {
    //Check host reachable only if connected to Router/Wifi/3G...etc
        if (hostReachable())
            $('#onlineStatus').html('ONLINE').removeAttr('class').addClass('online');
        else
            $('#onlineStatus').html('OFFLINE').removeAttr('class').addClass('offline');
    } else {
        $('#onlineStatus').html('OFFLINE').removeAttr('class').addClass('offline');
    }
}

function hostReachable()
{
    // Handle IE and more capable browsers
    var xhr = new (window.ActiveXObject || XMLHttpRequest)("Microsoft.XMLHTTP");
    var status;

    // Open new request as a HEAD to the root hostname with a random param to bust the cache
    xhr.open("HEAD", "//" + window.location.hostname + "/?rand=" + Math.floor((1 + Math.random()) * 0x10000), false);

    // Issue request and handle response
    try {
        xhr.send();
        return (xhr.status >= 200 && (xhr.status < 300 || xhr.status === 304));
    } catch (error) {
        return false;
    }

}

EDIT: Use port number if it is different than 80, otherwise it fails.

xhr.open("HEAD", "//" + window.location.hostname + ":" + window.location.port + "/?rand=" + Math.floor((1 + Math.random()) * 0x10000), false);
Bogdan T Stancu
  • 404
  • 5
  • 6
  • This doesn't work always, that is why I asked this question in the first place. – Gaurav Aug 12 '15 at 14:20
  • At least you're the first to realise that `online` doesn't actually mean you're online, just connected to a network that may or may not even have internet. – zanderwar Jun 07 '20 at 23:57