views:

28

answers:

1

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?

+3  A: 

Because the code doesn't run in sync as you'd expect from the coding. The $.post call 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 the alert() which displays 2. 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 the alert(). That's why you see the difference.

In this particular code example, you should have noticed that by seeing 2 being alerted before 3. Try adding more sensible information to the alert, e.g.

alert('Inside $.post callback: ' + $("#finalvalue").val());

and

alert('At end of function: ' + $("#finalvalue").val());

All with all, if you want to do some stuff based on the new data, the code should then go inside the callback function.

BalusC