I have this code :
function getJSONVideoInformation(videoUrl, informationPath) {
var jsonPath = 'https://www.googleapis.com/youtube/v3/videos?key=' + googleAPIKey + '&part=snippet&id=' + getVideoId(videoUrl);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
var object = JSON.parse(xhr.responseText);
paths = informationPath.split('.'),
for (var i = 0, informationToReturn = object; informationToReturn && i < paths.length; i++) {
informationToReturn = informationToReturn[paths[i]];
}
console.log(informationToReturn);
return informationToReturn;
}
}
};
xhr.open('GET', jsonPath, true);
xhr.send();
}
var newP = document.createElement('p');
newP.innerHTML = getJSONVideoInformation(videoUrl, 'items.0.snippet.title');
My goal is to display newP with 'informationToReturn' as text. When I execute the code everything seems to work, the console.log in the function shows the good value in the console (which is text) but newP only displays 'undefined'.
I can't figure out what's wrong :c
Thanks!