0

I am storing the return of a function in a variable. That variable is always undefined. I have no idea why and i am hoping fresh eyes may be able to help me.

Strat Script code

function getUserInfo(data){
    var params = {type:'userinfo',data:data};
    $.ajax({
        url: DOMAIN_NAME + "get.php",
        dataType: 'text',
        type: 'post',
        contentType: 'application/x-www-form-urlencoded',
        data: params,
        success: function( data, textStatus, jQxhr ){
            var response = JSON.parse(data);
            if (response.result == "success"){
                console.log(response.data); //Correct Data
                return response.data;
            }else{
                alert(response.data);
                return false;
            }
        },
        error: function( jqXhr, textStatus, errorThrown ){
            alert("Something went wrong, try again later.");
            return false;
        }
    });
}

Here , call function getUserInfo()

console.log(getUserInfo(window.localStorage.getItem("auth"))); //Undefined??
var userInfo = getUserInfo(window.localStorage.getItem("auth"));
console.log(userInfo); //Undefined??

Incase it is relevant the returned json from get.php looks like this

{"result":"success","data":"FOOBAR"}
sanjay sisodiya
  • 455
  • 4
  • 14
Mattigins
  • 1,014
  • 9
  • 25

1 Answers1

0

I believe this is because of JavaScript being asynchronous. What you should do is return a Promise instead. This is an example of my code from a project using MySQL. The principle should be the same.

async function getUserInformation(id) {
    let query = `SELECT full_name,description,link,htb FROM users WHERE discord_id = ${id}`;
    return new Promise((resolve, reject) => {
      pool.query(query, function (err, result) {
        if (err) throw err;
        resolve(result)
      })
    })
  }

Then, to use the result from this function, you do

    getUserInformation(id).then((result)=>
    // Do operations with result here
    ).catch(console.error)

Essentially, the idea is to return a Promise, which can resolve or reject. Once your promise is resolved, you are able to use the result from that to perform whatever operations you need. Such is the annoyance of JavaScript being asynchronous.

Haolin
  • 161
  • 5