Ark wrote:That value is undefined because when you make an AJAX call it's an asynchronous call. Meaning that it will perform in the background, while your script is still running normally. So that's why it first logs undefined, and then when the AJAX call has finished your callback function is called modifying aValue.
Hope that made sense.
This is correct. At the $.post() call, the single-thread of JS execution immediately goes back to finish more code while the AJAX call awaits a response to run its callback (the callback that actually sets aValue), so it runs the console.log(aValue) statement, at which point it is undefined. At some point after that (a few milliseconds later), the AJAX response is received and then aValue is set, but it is too late. This is how you would need to structure this to work asynchronously:
Code: Select all
<script>
var aValue;
function dothis()
{
getID("peter","pan");
}
function getID(a,b)
{
$.post('getID.php', {aname: a, apass: b},
function (fbdata)
{
aValue = fbdata;
console.log(aValue); // data as from the PHP script, so, that works...
}
);
}
</script>
You already had a console.log() call inside the callback of the $.post call, so I just removed the console.log that was in the wrong place.
In asynchronous programming, you have to put all the code that relies on the result of an asynchronous method call inside the asynchronous method's callback. Otherwise the code that is relying on this result will run a split second after the asynchronous call is made, but before the results are returned back. Take a look at this psuedocode:
Code: Select all
var health = 100;
ascycHealthUpdate(function(newHealth){
health = newHealth;
});
console.log(health);
Although the asyncHealthUpdate function is returning an update for health, that isn't what will be printed out to the console. The function to get the updated health will be fired off, but before the results return, 100 will be logged to the console. The code instead would need to be written like this:
Code: Select all
var health = 100;
ascycHealthUpdate(function(newHealth){
health = newHealth;
console.log(health);
});
You can also use methods to keep from having to repeat blocks of code when you need different paths through the code, etc:
Code: Select all
var printHealth = function(sHealth) {
console.log(sHealth);
};
var health = 100;
ascycHealthUpdate(function(newHealth){
printHealth(newHealth);
});
Of course, printing the health in this case was trivial, but I used methods all the time to "finish-off" async callbacks.
Really getting the hang of asynchronous programming takes a while. Often in client-side Javascript, it isn't much of an issue, and many devs can code fine in it for months or even years without understanding it. If you ever learn an exclusively asynchronous platform that requires tons of concurrency, such as Node.js, it is always right in your face. That really forces you to learn patterns for asynchronous programming
