0

I would like to get an array with objects from json using XMLHttpRequest() and assign it to a variable.

If i log it in a console it shows the array.

function getData() {
  let myJson = [];
  var xhr = new XMLHttpRequest();
  var url = 'https://www.reddit.com/r/funny.json';

  xhr.onreadystatechange = function () {

    if (xhr.readyState == 4 && xhr.status == 200) {
      var jsonData = JSON.parse(xhr.responseText);
      arr = jsonData.data.children;

      for (let i = 0; i < arr.length; i++) {
        let newObject = {};
        newObject.title = arr[i].data.title;
        newObject.upvotes = arr[i].data.ups;
        newObject.score = arr[i].data.score;
        newObject.num_comments = arr[i].data.num_comments;
        newObject.created = arr[i].created_utc;
        myJson.push(newObject);
      }
    }
  };
  xhr.open("GET", url, true);
  xhr.send();
  return myJson;
}

let data = getData();

console.log(data[0]);

But if I try to do anything with (console.log(data[0]);) it it returns undefined. What am I doing wrong? Thanks for any explanation! Cheers.

  • 2
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – AuxTaco May 24 '19 at 15:18

3 Answers3

1

Just pass in the callback function instead of returning the value from an asynchronous XML HTTP request.

function getData(callback) {

  var xhr = new XMLHttpRequest();
  var url = 'https://www.reddit.com/r/funny.json';

  xhr.onreadystatechange = function() {

    if (xhr.readyState === 4 && xhr.status === 200) {
      var jsonData = JSON.parse(xhr.responseText);
      arr = jsonData.data.children;

      let myJson = [];
      for (let i = 0; i < arr.length; i++) {
        let newObject = {};
        newObject.title = arr[i].data.title;
        newObject.upvotes = arr[i].data.ups;
        newObject.score = arr[i].data.score;
        newObject.num_comments = arr[i].data.num_comments;
        newObject.created = arr[i].created_utc;
        myJson.push(newObject);
      }

      // Invoke the callback now with your recieved JSON object
      callback(myJson);
    }
  };

  xhr.open("GET", url, true);
  xhr.send();
}

getData(console.log);
Kunal Mukherjee
  • 5,775
  • 3
  • 25
  • 53
0

Your return happens outside of the onreadystatechange. So you exit before you even have the data.

Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176
0

Pass in a callback function to call when you have the data, or have the asynchronous call return a JS Promise that resolves with the gotten data.

Kyle P
  • 54
  • 9