I have a function that finds the name of the user from the database, according to the input userID. But I am facing difficulty in returning the name.
function getName(userID){
var user = { "username" : userID};
var name;
$.get("/getName",user,function(data,status){
console.log(data); //prints correct result
return data; //but returns undefined
});
}
The returned value is always undefined. The calling function looks like this :
function init(){
myid = "james123";
myname = getName(myid);
console.log(myname); //always prints undefined
}
If I try to save the data received from the database in a variable, and return it later, like :
function getName(userID){
var user = { "username" : userID};
var name;
$.get("/getName",user,function(data,status){
console.log(data);
name = data;
});
return name;
}
This also doesn't work and I know because it is asynchronous. Any way to make this return work?