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.
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.
Your function sessionStatus() doesn't return anything, hence the alert says undefined.
All the function does is set thing up for the AJAX call to happen once the page loads - nothing actually happens within sessionStatus() that could be returned.
The code in function(status) { ...} doesn't get run until the AJAX call to the server returns a value, and that AJAX call doesn't get sent until the page loads.
You ought to read up on what $.getJSON() and $(document).ready() actually do, because you're going to continue to get confusing behaviour until you understand them properly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With