The code:
$.post('script.php',{value:value},function(data)
{
var Aquaman= ???;
});
Now my question is if I want to set the data value into the Aquaman variable, how do I do it?
The code:
$.post('script.php',{value:value},function(data)
{
var Aquaman= ???;
});
Now my question is if I want to set the data value into the Aquaman variable, how do I do it?
Welcome to the wonderful world of asynchronous logic.
All you need to do is var Aquaman = data;
-- however, that variable will ONLY exist inside that anonymous function.
You can get around this by assign global variables in the usual manner:
var Aquaman;
$.post('script.php',{value:value},function(data) {
Aquaman= data;
});
However, this global variable won't be set until after your AJAX call is completed. This may be desirable if, for instance, Aquaman
is being called by other AJAX calls or user events. However, the following code won't work as you might expect:
var Aquaman;
$.post('script.php',{value:value},function(data) {
Aquaman= data;
});
console.log(Aquaman); // displays nothing
...because console.log()
is run immediately and before the $.post()
is completed.
The only way to prevent that is to make a synchronous AJAX call:
$.ajax({url: 'script.php', data: {value:value}, async: false}, function(data) {...});
...but this nullifies most of the advantages of AJAX by forcing your script to stop and wait for the callback to complete. In almost all cases, it's better to let your AJAX remain asynchronous and deal with the data
inside the callback.