Gaurav
Gaurav

Reputation: 1045

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?

Upvotes: 12

Views: 41051

Answers (8)

lincolndu
lincolndu

Reputation: 105

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>

Upvotes: 1

Muhammad Tahir
Muhammad Tahir

Reputation: 2491

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();

Upvotes: 4

Fezal halai
Fezal halai

Reputation: 784

100% Working:

function checkconnection() {
    var status = navigator.onLine;
    if (status) {
        alert('Internet connected !!');
    } else {
        alert('No internet Connection !!');
    }
}

Upvotes: 4

Bogdan T Stancu
Bogdan T Stancu

Reputation: 404

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);

Upvotes: 0

Stanley Amos
Stanley Amos

Reputation: 232

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!");
    }
});

Upvotes: 6

Beetroot-Beetroot
Beetroot-Beetroot

Reputation: 18078

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

Upvotes: 11

Mahmoude Elghandour
Mahmoude Elghandour

Reputation: 2931

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

Upvotes: 1

gurvinder372
gurvinder372

Reputation: 68393

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'
});
}

Upvotes: 0

Related Questions