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.
To make it simple to a so basic question, declare your Aquaman variable in global scope:
var Aquaman;
function something()
{
$.post('script.php',{value:value},function(data)
{
Aquaman= data;
});
}
You can find better way to do this, see there.
Assigning the value of data
to Aquaman
is as easy as the following:
$.post('script.php',{value:value},function(data){
var Aquaman= data;
});
However, because of variable scope if you need this value outside of the $.post
callback you need to define Aquaman
outside of this function. For example:
//Some Code
$.post(...,function(data){
var Aquaman = data;
});
// Aquaman is undefined out here.
However:
var Aquaman;
$.post(...,function(data){
Aquaman = data;
});
// Aquaman exists (but be careful, AJAX calls make this value not accessible
// until the callback has been executed.)