I am trying the new Twitch API and new to Jquery Ajax. I have successfully completed an Ajax request (for a list of top games) and output it on the console log and inspected the console results to ensure that the results are valid.
However, I am unable to parse the Json successfully into HTML for display:
1) The output shows 'undefined'
2) It is not iterating through the whole Json result set (shows 2 instead of 19 results)
Any advice? Thank you
New Twitch API reference: https://dev.twitch.tv/docs/api/reference/#get-top-games
<script>
$.ajax('https://api.twitch.tv/helix/games/top',
{
headers: {
"Client-ID": 'XXXXXXXXXXXXXXXXX'
},
dataType: 'json',
success: function ( data ) {
var content = '';
$.each(data, function(index, element){
content += 'id: ' + element.id + '<br />';
content += 'name: ' + element.name + '<br />';
$('#output').html(content);
});
}
})
.then(console.log);
</script>
</head>
<body>
<div id="output"></div>
</body>
In the documentation you can see that there is a data
property returned in the response. As such you need to iterate through data.data
, not just data
. The first data
refers to the entire object you receive through the argument to the success
handler, the second data
refers to the property within that object.
To save confusion it would be worth renaming the argument in the success
handler, to response
for example.
Also note that you're appending the content
in every iteration of your loop, even though you add more to it in the following iteration. As a result this will duplicate all the previous text nodes. To fix this, move the html()
call outside of the loop. Try this:
success: function(response) {
var content = '';
$.each(response.data, function(index, element) {
content += 'id: ' + element.id + '<br />';
content += 'name: ' + element.name + '<br />';
});
$('#output').html(content);
}