0

I am sending a post command to the webserver hosting my HTML file and I am using jquery to do so.

When I try to read the global variable with alert() it says 0 but in the returnData function, it gives me what the server returned.

<script src = "jquery.js"></script>
<script>

var faces = 0;

postList()

alert(window.faces) //gives me 0

//function with the post command
function postList(){
  $.post("/",{command : "2"},returnData);
}

function returnData(returnData,status){
  //try to save the data
  window.faces = returnData;
  alert(window.faces); //gives me the data from the server
}

</script>
Josh Harold
  • 103
  • 7
  • 1
    Duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Tyler Roper Dec 09 '19 at 19:50
  • https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron – epascarello Dec 09 '19 at 19:51

1 Answers1

1

HTTP Request is an asynchronous operation, so it will be processed after all synchronous code. Read more about JavaScript Event Loop. But in general, JavaScript will set the variable value to 0, then make an HTTP request with postList() which will call returnData() only after the rest of synchronous code, which contains alert(), so at the time of calling alert() value of the variable would be 0.