The reason it works when you introduce the alert is because it stops execution and gives enough time for the asynchronous call to finish.
You're not getting the right value because by the time the post request is finished and the callback is executed your javascript has already finished executing.
You have a few options here:
- Declare a global variable and perform a synchronous call, you can either do it with the code ABC posted or call
$.ajaxSetup({ async: false })
before your POST call. Assign the return value to the global variable and validate against that.
- use jQuery's ajaxStop:
$(document).ajaxStop(function() { //check your values here, still need to declare a global });
- Write the value to a hidden div/as an attribute anywhere in the DOM and have a timer that periodically checks it until there's a value.