Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check Internet connectivity with jquery

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?

like image 290
Gaurav Avatar asked Nov 18 '13 08:11

Gaurav


2 Answers

$.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.

like image 57
Beetroot-Beetroot Avatar answered Nov 07 '22 03:11

Beetroot-Beetroot


100% Working:

function checkconnection() {
    var status = navigator.onLine;
    if (status) {
        alert('Internet connected !!');
    } else {
        alert('No internet Connection !!');
    }
}
like image 26
Fezal halai Avatar answered Nov 07 '22 03:11

Fezal halai