I am trying to grab the viewer count of a Twitch channel using JavaScript and insert it into the phrase "CURRENTLY LIVE WITH VIEWERS." It currently returns "CURRENTLY LIVE WITH NaN VIEWERS." Why does it do this, and how can I fix it?
<p id="live"></p>
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
$.ajax({
url:'https://api.twitch.tv/kraken/streams/DailyMafia',
dataType:'json',
success:function(stream) {
document.getElementById("live").innerHTML="CURRENTLY LIVE WITH ".concat(parseInt(stream.viewers), " VIEWERS.");
},
error:function() {
document.getElementById("live").innerHTML="CURRENTLY OFFLINE.";
}
});
</script>
The value in the success callback function isn't actually just the object containing the information in the request, but is rather an object that contains the stream object. Thus, you're not actually accessing what you think you are and need to change this up a little bit.
Try the following:
<p id="live"></p>
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
$.ajax({
url:'https://api.twitch.tv/kraken/streams/DailyMafia',
dataType:'json',
success:function(stream) {
document.getElementById("live").innerHTML="CURRENTLY LIVE WITH ".concat(parseInt(stream.stream.viewers), " VIEWERS.");
},
error:function() {
document.getElementById("live").innerHTML="CURRENTLY OFFLINE.";
}
});
</script>