aymen taarit
aymen taarit

Reputation: 404

localStorage issue when doing ajax

I have some simple code that will run to check Internet connectivity and I'm using localStorage to hold the variable value and yet when I run it the value of that variable isn't effected. So, what can I do to fix it. Please help. If the state is changed to true the submit will happen else otherwise it will be prevented.

localStorage.setItem("state","");

function checkConnection(){             
   $.ajax({
       url:"assets/ping.js",
       success:function(res){
            localStorage.setItem("state","true");
       },
       onerror:function(){
            localStorage.setItem("state","false");
       } 
   });
 }

$("form").submit(function(e){

   checkConnection();

   if(localStorage.getItem("state") == "false"){
        return false;
   } else if(localStorage.getItem("state") == "true") {
        return true;
   }

});

Upvotes: 1

Views: 2577

Answers (1)

Adam
Adam

Reputation: 44929

This is a sychronization isssue. Your API call to check the connection does not complete before the form is submitted. You want the AJAX call to block until it gets a response. (actually I guess it should be called SJAX for synchronous).

You have to add async is false to the settings parameter. Read: http://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings

Here is how you do that with jQuery:

$.ajax({
   url:"assets/ping.js",
   async: false
   success:function(res){
       localStorage.setItem("state", "true");
   },
   error: function(){
        localStorage.setItem("state","false");
   }           
});

Also note that the error handler should be under error not onerror.

Finally, if all you are trying to do is detect if the Internet connection was lost you can do that on most browsers by checking the value of window.navigator.onLine. See: http://www.whatwg.org/specs/web-apps/current-work/#browser-state

Upvotes: 4

Related Questions