I'm trying to get a value from a callback, but it returns an undefined value. Below is the code I'm using:
function getJSON(url, callback) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if (callback) return callback(this.responseText);
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
function getUserName() {
getJSON("this is my url", function(resultJSON) {
return JSON.parse(resultJSON).user[0].displayName;
});
}
var userN = getUserName();
document.getElementById("username").innerHTML = "Hi " + userN;
I know this has been asked a billion times but I can't get it working the way I need with previous answers. The html element is still giving a "Hi undefined". Any thought or suggestion?