I have a function that gets information from JSON then inserts it into an array.
I then make the function return the array.
I want the code to work like so:
user = getUserInfo();
console.log(user["fname"]);
function getUserInfo(){
userArray = new Array();
var url = "./php/getUserInfo.php";
$.getJSON(url, function( data ) {
userArray["fname"] = data[0].first_name;
userArray["lname"] = data[0].last_name;
userArray["username"] = data[0].username;
console.log(userArray["fname"]);
});
return userArray;
}
When I log the value of the userArray[“fname”] in the function, it works perfectly.
When I log the value of userArray[“fname”] after the function has been called, I get
“undefined”
Why is this so?
You are returning the array outside of the
getJSONcallback. Because the call is asynchronous, you won’t be able to “return” the data in a traditional sense, but you can call another method and pass the array to it after it has been created.After the series of calls,
userwill bet set to theuserArrayarray.