Look this code:
<input type="hidden" id="finalvalue" value="2" />
<script>
$.post("/increment_in_one", { param: 2 }, function (data) {
alert( data ); // this shows: 3
$("#finalvalue").val( data );
alert( $("#finalvalue").val() ); // this shows 3
});
alert( $("#finalvalue").val() ); // this shows 2
</script>
Why does the last alert show 2?
Because the code doesn’t run in sync as you’d expect from the coding. The
$.postcall executes asynchronously “in the background”. As soon as you call$.post, the webbrowser will spawn a new thread which does all the task and the current thread just immediately continues with the remnant of the function, which is thealert()which displays2. The new background thread in turn connects the webserver, fires a HTTP POST and then finally invokes the callback function. It takes more time than the initial thread needs to call thealert(). That’s why you see the difference.In this particular code example, you should have noticed that by seeing
2being alerted before3. Try adding more sensible information to the alert, e.g.and
All with all, if you want to do some stuff based on the new data, the code should then go inside the callback function.