I’m in the process of changing the way my website gets Twitch data from API calls where I was using PHP and I need to use AJAX to get them. I’m able to get the authentication barear token but I’m having problems passing the token to another AJAX function that gets API data of a video.
Any ideas on what I’m doing wrong?
$.ajax({
type: “GET”,
url: “https://id.twitch.tv/oauth2/token?client_id=xxx&client_secret=xxx&grant_type=client_credentials”,
header: {
“Content-Type”:“application/x-www-form-urlencoded”
},
success: function (data) {
var a = JSON.parse(JSON.stringify(data.access_token)); // This line has the token
$.ajax({
type: “post”,
url: “https://api.twitch.tv/helix/videos?id=1493894959”,
header: {
'Authorization: Bearer ’ + a,
'Client-Id: ’ + ‘xxx’,
},
success: function (data) {
$(".text").text(JSON.parse(JSON.stringify(data.items[0].snippet.description)));
}.
dataType: ‘JSON’,
});
},
dataType: ‘JSON’,
});
})
First of all, this is a WordPress site and this is all in the backend, nothing is publicly exposed. All it does it store data into fields and then displays them.
Here’s what I got working:
$.ajax({
type: “POST”,
url: “https://id.twitch.tv/oauth2/token?client_id=<?php echo $client_ID;?>&client_secret=<?php echo $client_secret;?>&grant_type=client_credentials”,
header: {
“Content-Type”:“application/x-www-form-urlencoded”
},
success: function (data) { // authentication token
$.ajax({
type: “GET”,
url: “https://api.twitch.tv/helix/videos?id=1493894959”, // Video ID from URL
headers: { // this was giving me problems
“Client-ID”: <?php echo $client_ID;?>
“Authorization”: "Bearer " + JSON.parse(JSON.stringify(data.access_token)) // token from eariler AJAX
},
success: function (data) {
$(’.text’).text(JSON.stringify(data)); // show output
},
dataType: ‘JSON’,
});
},
dataType: ‘JSON’,
});