javascriptjqueryajax

JQuery and JS variables


a little misunderstanding with JQuery and JS variables. Simple example:

function someFunc(){

   var flag = true;

    $(function(){
        $.post("/some/address/", {} ,function(data){
            if( data == false){             
                flag = false;
            }
        });
    });
   if(flag == false){
      return false;
   }    
} 

The main problem is accessibility of variable flag in Jquery functions. I always get the same flag value equal to true. How to make this done ? How to make global variable to be visible for JS and JQuery ?


Solution

  • I don't think your problem here is one of scope, actually; I think your problem is that the post function is asynchronous. That is, it goes off to the server to get data, and runs the callback function (which updates your flag) when the data comes back (which might take a while). But meanwhile, the surrounding function keeps on going; it doesn't wait for the post to return. So the flag update happens after the outer function has returned.