Saturday, May 11, 2024
 Popular · Latest · Hot · Upcoming
102
rated 0 times [  103] [ 1]  / answers: 1 / hits: 32272  / 15 Years ago, fri, november 13, 2009, 12:00:00

I have a problem returning a variable in my function, the below script works fine:



function sessionStatus(){
$(document).ready(function(){
$.getJSON(scriptRoot+sessionStatus.php,function(status){
alert(status);
});
});
}

sessionStatus();


Bet when I try the following I get a message box with the message undefined:



function sessionStatus(){
$(document).ready(function(){
$.getJSON(scriptRoot+sessionStatus.php,function(status){
return status;
});
});
}
alert(sessionStatus());


This is really bugging me, I just can't seem to see what I've done wrong.


More From » function

 Answers
16

There are two things you should know:



1: the JSON thing is asynchronous, so the function call to sessionStatus could already be done when the JSON is still being fetched. The following would work:



function sessionStatus(callback){
$(document).ready(function(){
$.getJSON(scriptRoot + sessionStatus.php, function(status){
callback(status);
});
});
}
sessionStatus(function(s){alert(s);});


or rather:



function sessionStatus(callback){
$(document).ready(function(){
$.getJSON(scriptRoot + sessionStatus.php, callback);
});
}
sessionStatus(function(s){alert(s);});


2: even when it would be synchronous, you are only giving a return value from the inner function, so the sessionStatus would return nothing. Check out this code (not related to your JSON thing):



function do() {
var x = 0;
(function(){
x = 2;
})();
return x;
}


or:



function do() {
var x = (function(){
return 2;
})();
return x;
}


Both return 2. Hopefully this explains a bit.


[#98317] Tuesday, November 10, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cayden

Total Points: 314
Total Questions: 107
Total Answers: 101

Location: Slovenia
Member since Wed, Apr 6, 2022
2 Years ago
;