Q:

Display JSON Request

<html>
<head>
<script>
var request = new XMLHttpRequest();
request.open('GET', 'https://www.googleapis.com/youtube/v3/channels?part=statistics&id=UCiWypivJjO5CIQPVVfFlVQA&key=AIzaSyD5FVw6fP3ingbjTvUEzm-EYctX2ytfL2Y', true);

request.onload = function() {
  if (request.status >= 200 && request.status < 400) {
    // Success!
    var data = JSON.parse(request.responseText);
  } else {
    // We reached our target server, but it returned an error

  }
};
</script>
</head>
<body>
</body>
</html>

My problem is simple, I have requested the JSON YouTube v3 Data API, however, I'd like to display data requested from the link: https://www.googleapis.com/youtube/v3/channels?part=statistics&id=UCiWypivJjO5CIQPVVfFlVQA&key=AIzaSyD5FVw6fP3ingbjTvUEzm-EYctX2ytfL2Y Namely the subscriber count, how would I be able to use this GET request to load the number of subscribers into the innerHTML of an element? What do I have to do?

A:

Using the object you get by parsing the JSON (data), get the subscriberCount value and place it into a div or other element using .innerHTML. Make sure you use request.send() to actually send your AJAX request.

<html>
<head>
<script>
var request = new XMLHttpRequest();
request.open('GET', 'https://www.googleapis.com/youtube/v3/channels?part=statistics&id=UCiWypivJjO5CIQPVVfFlVQA&key=AIzaSyD5FVw6fP3ingbjTvUEzm-EYctX2ytfL2Y', true);

request.onload = function() {
  if (request.status >= 200 && request.status < 400) {
    var data = JSON.parse(request.responseText);
    document.getElementById("subs").innerHTML = data.items[0].statistics.subscriberCount;
  } else {
    // We reached our target server, but it returned an error
  }
};

request.send();
</script>
</head>
<body>
<div id="subs"></div>
</body>
</html>

