How to check the internet connection in mobile application

Android, Cordova, 2015-06-16 23:53:53 UTC

In mobile applications using the Cordova framework, it is fairly easy to determine the device connected to the internet or not. You don't need a plugin for this job. It can be done easily with jQuery ajax technique.

The concept of this technique is quite simple; the device send some package of data and wait for response from the server. If the server doesn't response correctly, this can be the device is not connected to the internet.

Here is the example code;

$.ajax({
    url: 'http://example.com/api/check_conn',
    timeout: 10000,
    success: function(response) {
        alert('connected'); 
    }, 
    error: function(jqXHR, textStatus, errorThrown) {
        if(t==="timeout") {
            alert("timeout"); 
        }
        else {
            //you can say like bellow
            //alert('No data connection'); 

            //or you can alert an textStatus
            alert(textStatus);
        }
    } 
});


You can take a look closer to the following excerpts which is taken from jquery documentation at api.jquery.com;

error 
Type: Function( jqXHR jqXHR, String textStatus, String errorThrown )
A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and cross-domain JSONP requests.

Share: