Reputation: 35
function get(){
$.get('/get.php', function(data) {
alert('one: ' + data)
return data;
});
}
var test = get();
alert('two:' + test);
In get.php is:
<?php echo "number"; ?>
why one alert show me one: number
but two alert show me two: undefined
How can i get this value outside function?
Upvotes: 1
Views: 172
Reputation: 30666
This is because when this statement is called, the function get() has already returned before the callback of $.get() has been executed. Keep in mind that ajax requests are asynchronous.
What are the execution steps:
To handle this case, you would typically pass the callback to execute as a parameter:
function get(callback) {
$.get('/get.php', function(data) {
if ($.isFunction(callback)) {
callback(data);
}
});
}
Upvotes: 1
Reputation: 4048
Your return data
is returning from the ajax anonymous function, not from the get() function.
Upvotes: 1
Reputation: 39223
The $.get
call is asynchronous. That means that you pass it a callback (your function(data) { ... }
, which gets executed with the result from the call. You can't return
from inside that callback - when it is executed, your outer function (doing the $.get
) has already returned. Instead, try something like this:
// callback will be executed with the response from your GET request
function get(callback){
$.get('/get.php', callback);
}
// Call get with a callback receiving the response
get(function(data) {
alert('two:' + data);
});
This is a pattern you will have to get used to when writing javascript code.
Upvotes: 7