Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get session value with jQuery

I would like to retrieve data from a session variable on a button click, without reloading the page. My getter function is the following one:

function GetSession()
{
    var value;

    function GetValue(data)
    {
        value = data;
    }

    $.get("sessionAPI.php?action=get", function(data) { GetValue(data); });
    return value;
}

Yet the "value" variable stays undefined after I call this function. How could I give the value of "data" to the "value" variable? Thanks for the answers!

like image 214
Strider2342 Avatar asked Jul 30 '26 09:07

Strider2342


1 Answers

You are trying to return a value from an asynchronous operation (i.e. that completes later). That will never work as it returns long before the result is available. You need to use callbacks or promises instead.

Using a callback the code looks like:

function GetSession(callback)
{
    $.get("sessionAPI.php?action=get", function(data) { callback(data); });
}

and use like this:

GetSession(function(value){
  // Do something with the session value
});

Using promises:

function GetSession()
{
    return $.get("sessionAPI.php?action=get");
}

and use like this:

GetSession().done(function(value){
  // Do something with the session value
});
like image 185
Gone Coding Avatar answered Aug 02 '26 00:08

Gone Coding



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!