Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to programmatically check availability of internet connection using jquery

I am developing android phonegap application.When i run the application without internet connection,it is force closed.so,I need to check the internet connection in the dom,before calling the ajax using jquery/javascript

Here is my sample code:

var a=navigator.onLine;
 if(a){
  alert('online');
$.ajax({
            type: "GET",
            url: url, 
            dataType: 'json',
            async: true, 
            cache: false,
            success: function(data){ 

                alert('success');
            },
            error: function(e){

                alert('error');
            }
    });
 }else{
  alert('ofline');
 }

But Am always getting the alert('online'),even when there is no internet connection.Please kindly guide me.Thanks in Advance

like image 595
Mercy Avatar asked Dec 28 '22 05:12

Mercy


2 Answers

As you specified in a tag, you can't access hardware specs without PhoneGap API, and to check the Available connection all you need is implement the Connection

The connection object gives access to the device's cellular and wifi connection information.

function checkConnection() {
    var networkState = navigator.network.connection.type;

    var states = {};
    states[Connection.UNKNOWN]  = 'Unknown connection';
    states[Connection.ETHERNET] = 'Ethernet connection';
    states[Connection.WIFI]     = 'WiFi connection';
    states[Connection.CELL_2G]  = 'Cell 2G connection';
    states[Connection.CELL_3G]  = 'Cell 3G connection';
    states[Connection.CELL_4G]  = 'Cell 4G connection';
    states[Connection.NONE]     = 'No network connection';

    alert('Connection type: ' + states[networkState]);
}

checkConnection();

Full Example available in PhoneGap Docs

like image 98
balexandre Avatar answered Dec 29 '22 19:12

balexandre


Maybe you could use the device's network connection state property:

var a = (navigator.network.connection.type != Connection.NONE);

Also see the "Connection" API

like image 23
scessor Avatar answered Dec 29 '22 19:12

scessor