0

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!

Alex K.
  • 171,639
  • 30
  • 264
  • 288
Victofu
  • 53
  • 2
  • 9
  • send() is asynchronous & returning a value in onreadystatechange is not going to work, do your work with the result where you call JSON.parse() – Alex K. Sep 11 '17 at 16:33
  • You're right, it works. But I need to create my newP outside of the function for some reasons, don't you have an idea on how I could fix it? – Victofu Sep 11 '17 at 16:44

1 Answers1

0

You shouldn't return from function that runs asynchronously. Replace the return statement with the last two lines of code.

Marcin Szwarc
  • 569
  • 3
  • 13
  • You're right, it works. But I need to create my newP outside of the function for some reasons, don't you have an idea on how I could fix it? – Victofu Sep 11 '17 at 16:47
  • Wrap that functionality (the last two lines) in its own function, and call it from within the callback. – Patrick Kunka Sep 11 '17 at 16:49
  • Add third argument for `getJSONVideoInformation` named for example `tag` and then use `xhr.onreadystatechange = function(tag) {`. – Marcin Szwarc Sep 11 '17 at 16:50