0

I know that the answer to this question is probably obvious, but I seem to be stuck, so I decided to ask a question.

Inside my jQuery $(document).ready function, I have created a variable called logged. I have set it up like this: var logged = 0;

Next I have a post block of code, which, based on the returned data will set the logged variable to 1 or not change it.

$.post("url/script.php",
function(d, s){
    if (s) {
        if (d == "1") {
            logged = 1;
        }
        if (d == "0") {
            //Do stuff
        }
    } else {
        //Do other stuff
    }
    console.log(logged); //Prints 1
}); 

Underneath that I have an if statement which checks to see if logged is 1 or not, but a console.log command above reveals that the logged variable has reset to 0:

console.log(logged); //Prints 0

if (logged == 1) {
    //Do stuff
}

Does anyone know why?

Thanks in advance.

Luke
  • 2,038
  • 3
  • 22
  • 46
  • It's not reset, it's being set in an asychronous call - and your `if` logic is running before the call is completed. – tymeJV Nov 19 '15 at 21:38

1 Answers1

2

I believe that this is because $.post() is an asynchronous function. Meaning, your Javascript continues to run while $.post() is still running. Your JS does not wait for it to return. So, by the time your console logs logged it is still set to 0

So in fact, it is not reset, it just has not yet been set to 1

To combat this you can set a variable to your post statement and check if it is done.

  var posting = $.post( url, function() );

  posting.done(function( data ) {
    //do something when complete
  });

you can read more about this in jQuery's API - http://api.jquery.com/jquery.post/

You should also take a look at this question which addresses making $.post() a synchronous call how to make a jquery "$.post" request synchronous

Community
  • 1
  • 1
Adjit
  • 10,134
  • 12
  • 53
  • 98