4

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

Mercy
  • 1,862
  • 9
  • 39
  • 75

2 Answers2

8

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

Ali Ben Messaoud
  • 11,690
  • 8
  • 54
  • 87
balexandre
  • 73,608
  • 45
  • 233
  • 342
  • Thanks for your reply.I have added this code.But in the alert always I am getting 'Cell 3G connection' even when there is no internet connection.Please kindly guide me.Thanks in Advance. – Mercy Feb 28 '12 at 08:06
  • you will **always have 3G connection** that is used through you data connection for your subscription! You need to say that you do not want 3G data... I know how to do it on the iPhone, but not on the Android... search for it. In the emulator, just disconnect from the internet to test it. – balexandre Feb 28 '12 at 08:26
  • Thanks.I have disabled the data-enabled settings in android emulator and while running the application, i am getting connection type:undefined .please guide me.Thanks in Advance. – Mercy Feb 28 '12 at 09:35
2

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

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

Also see the "Connection" API

scessor
  • 15,995
  • 4
  • 43
  • 54