How to get data of a youtube playlist in JSON format using JavaScript API V3 - youtube

Youtube stopped support to V2 I'm using till now, can anyone tell me how to get data of a youtube playlist in JSON format using JavaScript API V3
V2 URL I used is as given below
http://gdata.youtube.com/feeds/api/playlists/{PLAYLIST_ID}?alt=json-in-script&callback=showMyVideos
Resolved
v3 URL is
https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId={PLAYLIST_ID}&key={KEY}

There are a number of sample applications for the Javascript v3 client library that can be found here:
https://developers.google.com/youtube/v3/code_samples/javascript
The call you are probably after is PlaylistItems:list and can be seen here:
https://developers.google.com/youtube/v3/docs/playlistItems/list
and can be called using:
GET https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&id=YOUR-PLAYLIST-ID&key={YOUR_API_KEY}
Something along these lines will get details of the first 50 records in a specified playlist using the Javascript client library. The result is stored in the response object.
<!doctype html>
<html>
<head>
<title>YouTube</title>
</head>
<body>
<script>
function onGoogleLoad() {
gapi.client.setApiKey('{YOUR-API-KEY}');
gapi.client.load('youtube', 'v3', function() {
var request = gapi.client.youtube.playlistItems.list({
part: 'snippet',
playlistId: '{PLAYLIST-ID-HERE}',
maxResults: 50
});
request.execute(function(response) {
for (var i = 0; i < response.items.length; i++) {
console.log(response.items[i].snippet.title + " published at " + response.items[i].snippet.publishedAt)
}
});
});
}
</script>
<script src="https://apis.google.com/js/client.js?onload=onGoogleLoad"></script>
</body>
</html>

Related

Does the Dailymotion API have something equivalent to YouTube's onYouTubeIframeAPIReady?

With the YouTube JS API, I can do the following:
<script src="//www.youtube.com/player_api"></script>
<script language="javascript">
function onYouTubeIframeAPIReady() {
ytPlayer = new YT.Player('ytplayer');
}
</script>
This will load the API, and when its ready, assign ytPlayer.
However, the Dailymotion API is included as follows:
<script src="//api.dmcdn.net/all.js"></script>
<script>
DM.init();
</script>
This doesn't wait for the API to be ready. So I'll often get Uncaught ReferenceError: DM is not defined errors. Does Dailymotion have a way to wait for the API to be ready before it executes code?
The most efficient way to load the SDK in your site is to load it asynchronously: example loading asynchronously
You can then subscribe to the event 'apiready'
event subscribe documentation
list of events

Retrieve YouTube live_stats concurrent viewers from channel instead of specific live event video

I know that it is possible to get the number of concurrent viewers for a specific live streaming YouTube event with this link: https://www.youtube.com/live_stats?v={videoid}
I was wondering if is it possible to get the live_stats for a channel or playlist instead of a specific live event.
I want to embed this data in a webpage that will have multiple different live events occurring weekly. Changing the video id for each event will be a burden. If this can't be done directly, is there a way to get the video id of a current live event from a channel and use java script or php to replace the id in the link? Please help me figure this out.
After some time, I figured this out myself...
I created a PHP script that retrieves the video id of the first video in a playlist and puts the id into the live stats link. I take the link of live events and put them into a playlist for easy use.
<?php
// Retrieves video info from Youtube playlist. Just update [PLAYLIST_ID] and [API_KEY]
$json_url = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=1&playlistId=[PLAYLIST_ID]&fields=items%2Fsnippet%2FresourceId%2FvideoId&key=[API_KEY]";
$json = file_get_contents($json_url);
$json=str_replace('},
]',"}
]",$json);
$data = json_decode($json, true);
$videoId = $data['items'][0]['snippet']['resourceId']['videoId'];
$viewers = file_get_contents("https://www.youtube.com/live_stats?v=$videoId");
echo $viewers;
?>
I then created an HTML page where the data is dynamically updated using jQuery.
<html>
<body>
<div id="status" style="color: #666; line-height: 24px; font-size: 19px; font-weight: normal; font: 19px Roboto,arial,sans-serif;"></div>
<script src="http://code.jquery.com/jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
function update() {
$.ajax({
url: 'viewers.php',
dataType: 'text',
success: function(data) {
if (parseInt(data) == 0) {
$("#status").css({ display: "none" });
} else {
$("#status").text(parseInt(data) + ' watching now' );
}
}
})
}
update();
var statusIntervalId = window.setInterval(update, 5000);
</script>
</body>
</html>
This is how far I got. Now I am just wondering if there is a better way to combine these codes together to create less server requests. Each jQuery request happens every 5 seconds and is approximately 240 bytes is size. Even though the requests are small, they might still slow down a page.
If you can, please help me improve my solution. Thank you in advance.

WKWebView - Failed to load resource: Origin null is not allowed by Access-Control-Allow-Origin

I trying to read my local JSON file on IOS WKWebview. However Failed to load resource: Origin null is not allowed by Access-Control-Allow-Origin.
I'm using UIWebview before and it's work fine. However when i change to WKWebview this error happen.
$.ajax({
type: 'GET',
url: 'json_app/country_state_json.json?callback=?',
async: false,
jsonpCallback: 'jsonCallback',
contentType: 'application/json',
dataType: 'jsonp',
success: function(json)
{},
error: function(e) {}
});
Please assist.
Unfortunately, at this point WKWebView does not handle JavaScript asynchronously loading files using the "file://" protocol [1][2]. It works when the files are loaded from the DOM, just not using ajax or jQuery's .get (which is just abstracted ajax).
Here's a hack that I am simultaneously proud of and not proud of:
I have an app that needs to load a JSON object based on some dynamic information and then process it to display the web content. Originally, I was trying to have the JavaScript get the JSON file dynamically:
The old HTML:
<html>
<head>
<script type="text/javascript" src="makeContent.js"></script>
</head>
<body></body>
</html>
The old JSON:
{
"myData": true,
...
}
The old JavaScript:
$.get("data.json", function (data) {
// Process the data and generate the content
}, "json");
With this, I was encountering the same problem that you were. WKWebView would not load the data.json file.
My hack was to include the JSON content as another JavaScript object that is included in the DOM. The new JavaScript script simply assigns the JSON data as a string into a global variable. Note that this string needs to be a single line, as JavaScript doesn't support multiline strings. Then, this new script is dynamically inserted into the DOM when the WKWebView loads:
JavaScript Data file (replaces the JSON file):
var data = '{ "myData": true, ... }';
Swift:
let jsonInsertion = "var node = document.createElement('script');" +
"node.setAttribute('src', 'data.js');" +
"node.setAttribute('type', 'text/javascript');" +
"var head = document.getElementsByTagName('head')[0];" +
"head.insertBefore(node, head.childNodes[0]);"
webView?.evaluateJavaScript(jsonInsertion, completionHandler: { (_, error) in
print(error)
})
The resulting HTML:
<html>
<head>
<script type="text/javascript" src="data.js"></script>
<script type="text/javascript" src="makeContent.js"></script>
</head>
<body></body>
</html>
Now, your JavaScript should be able to access the data as a global variable, and convert it using JSON.parse(data). You might need to add some synchronization code to ensure that your script runs after the data script is inserted by the app.
Again, this is a hack, but it's working for me. Hopefully it might be useful to you until Apple allows the "file://" protocol.
I bet that you need to provide a full url in the request instead of a relative one. How about using:
url: document.URL + "/json_app/country_state_json.json?callback=",
(I removed the trailing ? - that is not correct and results in a malformed URL)

YouTube API Academy

I just completed the YouTube API tutorials on Codecademy and successfully managed to display results relating to a given 'q' value in the console window provided using the following code:
// Helper function to display JavaScript value on HTML page.
function showResponse(response) {
var responseString = JSON.stringify(response, '', 2);
document.getElementById('response').innerHTML += responseString;
}
// Called automatically when JavaScript client library is loaded.
function onClientLoad() {
gapi.client.load('youtube', 'v3', onYouTubeApiLoad);
}
// Called automatically when YouTube API interface is loaded (see line 9).
function onYouTubeApiLoad() {
// This API key is intended for use only in this lesson.
// See http://goo.gl/PdPA1 to get a key for your own applications.
gapi.client.setApiKey('AIzaSyCR5In4DZaTP6IEZQ0r1JceuvluJRzQNLE');
search();
}
function search() {
// Use the JavaScript client library to create a search.list() API call.
var request = gapi.client.youtube.search.list({
part: 'snippet',
q: "Hello",
});
// Send the request to the API server,
// and invoke onSearchRepsonse() with the response.
request.execute(onSearchResponse);
}
// Called automatically with the response of the YouTube API request.
function onSearchResponse(response) {
showResponse(response);
}
and:
<!DOCTYPE html>
<html>
<head>
<script src="search.js" type="text/javascript"></script>
<script src="https://apis.google.com/js/client.js?onload=onClientLoad" type="text/javascript"></script>
</head>
<body>
<pre id="response"></pre>
</body>
</html>
The problem I am having now is that I have taken this code and put it into my own local files with the intention of furthering my understanding and manipulating it work in a way which suits me, however it just returns a blank page. I assume that it works on Codecademy because they use a particular environment and the code used perhaps only works within that environment, I am surprised they wouldn't provide information on what changes would be required to use this outside of their given environment and was hoping someone could shed some light on this? Perhaps I am altogether wrong, if so, any insight would be appreciated.
Browser Console Output:
Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('file://') does not match the recipient window's origin ('null').
I also had the same problem but it was resolved when I used Xampp. What you have to do is install xampp on your machine and then locate its directory. After You will find a folder named "htdocs". Just move your folder containing both js and HTML file into this folder. Now you have to open Xampp Control Panel and click on start button for both - Apache and SQL server. Now open your browser and type in the URL:
http://localhost/"(Your htdocs directory name containing both of your pages)"
After this, click on .html file and you are done.

Consume WCF Rest Service in ASP.net using jquery

I am trying to consume a wcf rest api in a asp.net project using jquery. for doing so i have done:
Created a WCF Rest service source code can be downloaded from here.
Created a ASP.Net project to consume that restAPI using jquery. source code here.
In ASP .Net project on the click of button I am trying to call a REST service. But every time I gets two issues:
calling var jsondata = JSON.stringify(request); in TestHTML5.js throws an error saying "Microsoft JScript runtime error: 'JSON' is undefined"
When I press ignore it continues towards WCF Rest API call but it always returns error (Not Found) function. Rest API never gets called.
Thanks for every one's help in advance.
ANSWER:
Solution and source link can be found on this link.
I have looked at the sample code you provided and the problem is that you are violating the same origin policy restriction. You cannot perform cross domain AJAX calls. In your example the service is hosted on http://localhost:35798 and the web application calling it on http://localhost:23590 which is not possible. You will have to host both the service and the calling application in the same ASP.NET project. You seem to have attempted to enable CORS on the client side using ($.support.cors = true;) but on your service doesn't support CORS.
Another issue saw with your calling page (TestHTML5.htm) is the fact that you have included jquery twice (once the minified and once the standard version) and you have included your script (TestHTML5.js) after jquery. You should fix your script references. And yet another issue is the following line <script type="text/javascript"/> which is invalid.
So start by fixing your markup (I have removed all the CSS noise you had in your markup in order to focus on the important parts):
<!DOCTYPE html>
<html dir="ltr" lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>SignUp Form</title>
<script type="text/javascript" src="../Scripts/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="../Scripts/TestHTML5.js"></script>
</head>
<body>
<button id="Send" onclick="testHTML5OnClick();">
Send Me ID!
</button>
</body>
</html>
and then in your TestHTML5.js you could also clean a little bit. For example your service is listening for the following url pattern json/{id} and accepting only GET verbs and you are attempting to use POST which is not possible. In addition to that you are attempting to use the JSON.stringify method which doesn't make any sense with the GET verb. You should simply send the id as part of the url portion as you defined in your service.
function testHTML5OnClick() {
var id = 5;
var url = "../RestServiceImpl.svc/json/" + id;
var type = 'GET';
callLoginService(url);
}
function callLoginService(url, type) {
$.ajax({
type: type,
url: url,
success: serviceSucceeded,
error: serviceFailed
});
}
function serviceSucceeded(result) {
alert(JSON.stringify(result));
}
function serviceFailed(result) {
alert('Service call failed: ' + result.status + '' + result.statusText);
}
Did u add this reference?
script type="text/javascript" src="../../json.js"></script>
I have same problem and search i get this and this result

Resources