Reputation: 511
So I am trying to build this script that gets viewer count and follower count from twitch. I got the viewer count one working but not the follower count. Here is the api/json link with the info I need. Link
Here is the javascript:
<script type="text/javascript">
var twitchName = "tsm_wildturtle";
function showFollowers(b){
alert(b._total);}
$.getJSON("https://api.twitch.tv/kraken/channels/"+ twitchName +"/follows.json", function(b){document.getElementById("follows").innerHTML += b._total;});
</script>
It displays nothing when I do this in the html: Followers:<div id="follows"></div>
Am I targeting the section wrong? Can someone please help. Yes I am using a current version of jquery for the $.getJSON
Upvotes: 0
Views: 872
Reputation: 6344
From Wikipedia definition "JSONP is a communication technique used in JavaScript programs running in web browsers to request data from a server in a different domain, something prohibited by typical web browsers because of the same origin policy."
Here since its a cross domain request you could simply add the 'callback=?'
at the end
$.getJSON("https://api.twitch.tv/kraken/channels/tsm_wildturtle/follows.json?callback=?",
function(data){
//document.getElementById("follows").innerHTML += b._total;
alert(data._total);
});
See working demo here
Upvotes: 2
Reputation: 50787
The issue here is that your browsers limitations are subject to Cross Origin Resource Sharing. Twitch does not have Access-Control-Allow-Origin:*
and therefore you're not allowed to fetch the data from your browser.
However, you can use server side code to get the data that you want and send it back .
$.ajax({
url: '/get_twitch_user.php',
data: {"twitchName" : twitchName},
success: function(data){
console.log(data);
}
});
Then at the server, in your get_twitch_user.php file
if(isset($_GET['twitchName'])):
echo json_decode(file_get_contents('https://api.twitch.tv/kraken/users/'.$_GET['twitchName']));
endif;
This will absolve you of the issue you're experiencing in regards to CORS.
Upvotes: 2