Get session value using jQuery

I would like to get data from a session variable on a button click without reloading the page. My getter function is as follows:

function GetSession()
{
    var value;

    function GetValue(data)
    {
        value = data;
    }

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

      

But the variable "value" remains undefined after calling this function. How can I assign the "data" value to the "value" variable? Thanks for answers!

+3


source to share


1 answer


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

Using the callback, the code looks like this:

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
});

      

+3


source







All Articles