Reputation: 360
We have a working PHP function that grabs specific YouTube video information using YouTube API v3.
We're trying to use JavaScript (jQuery) to do the same thing. The issue is that using our PHP function causes the page to load very slowly while it's retrieving the data. We're hoping that using JavaScript will allow our page to load before (or during) the data requests from YouTube.
First of all, this is an example url for one of our videos (you will need an API key to see the returned information yourself):
https://www.googleapis.com/youtube/v3/videos?part=statistics&id=ce5KbCTfHoA&key={YOUR_API_KEY}
That specific url will return this information:
{
"kind": "youtube#videoListResponse",
"etag": "\"jOXstHOM20qemPbHbyzf7ztZ7rI/qRFx1vTFF-k7dkRzNB5rGQ-dqiQ\"",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 1
},
"items": [
{
"kind": "youtube#video",
"etag": "\"jOXstHOM20qemPbHbyzf7ztZ7rI/2yn7rCfXCu0o-GNVtMEQqYssSpE\"",
"id": "ce5KbCTfHoA",
"statistics": {
"viewCount": "33169",
"likeCount": "281",
"dislikeCount": "3",
"favoriteCount": "0",
"commentCount": "85"
}
}
]
}
We are trying to retrieve the likeCount and dislikeCount of this video using JavaScript.
We can achieve this using PHP in the following manner:
function getVideoRatings() {
$JSON = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=statistics&id={VIDEO_ID}&key={YOUR_API_KEY}");
$json_data = json_decode($JSON, true);
$likes = $json_data['items'][0]['statistics']['likeCount'];
$dislikes = $json_data['items'][0]['statistics']['dislikeCount'];
/* some other code... */
}
This successfully parses the json information returned by google and returns the likes (likeCount) and dislikes (dislikeCount) for the video.
We'd like to do this using JavaScript (jQuery). Can anyone please help me figure this out?
I really appreciate any help or bump in the right direction.
Thanks
Upvotes: 2
Views: 89
Reputation:
$.getJSON("https://www.googleapis.com/youtube/v3/videos?part=statistics&id=ce5KbCTfHoA&key={YOUR_API_KEY}", function( data ) {
var likes = data['items'][0]['statistics']['likeCount'];
});
This should work. Use jQuery documentation.
Upvotes: 2