Search code examples
javascriptjqueryajaxcordovajquery-mobile

how to check net connection through ajax call


We tried to check authentication.We have username and password.We need if net_Work is available in mobile.authentication check through online. internet is not in mobile We need show alert first connected internet Ajax call authentication check :-

function authentication()
{
 username=$("#name").val();
 password=$("#psw").val();
$('#empty').append("Authentication  Will be Checking.......");
$.ajax({
        url: 'http://183.82.0.221:1234/MyService.svc/GetAuthenticatedUserData/'+username+'/'+password+'',
        dataType: 'jsonp',
        type:'get',
        cache:false,
        success:function(data) {
 if(data==1)
 {
 first();
 }
 else
 {
 alert("Authentication Failed");
 }
}
});
}

Above code is only if internet have mobile.it's working fine. If mobile don't have internet it's not response any thing.

if mobile don't have internet, We need Show alert("this app need internet so Please connect first");


Solution

  • If you are using html5 then the solution is very simple.There is a property in javascript

     navigator.onLine
    

    by using this property you can check that there is internet connectivity or not.If there is internet connectivity then make ajax call else store your data in browser localstorage and push it back to server when application get internet connected.

    Now If you are using html4 then the solution will be little bit tricky.In ajax call there is one more event listener that is "error".So you can make offline work by righting code in such a manner.

    error: function(x, t, m) {
        if(t==="timeout") {
            alert("Means there is no internet connectivity");
            now_run_your_offline_function()
        } else {
            alert(t);
        }
    

    Here t can be "timeout", "error", "notmodified" and "parsererror"

    In case you are using phone gap.Then check this solution. Android 2.3 and Phonegap, navigator.online does not work

    In your case final code will be.

    function authentication()
    {
     username=$("#name").val();
     password=$("#psw").val();
    $('#empty').append("Authentication  Will be Checking.......");
    $.ajax({
        url: 'http://183.82.0.221:1234/MyService.svc/GetAuthenticatedUserData/'+username+'/'+password+'',
        dataType: 'jsonp',
        type:'get',
        cache:false,
        timeout: 1000,
        error: function(x, t, m) {
    if(t==="timeout") {
        alert("Means there is no internet connectivity");
    } else {
        alert(t);
    }},
        success:function(data) {
     if(data==1)
    {
    first();
    }
    else
     {
     alert("Authentication Failed");
    }
    }
    

    }); }