i've tried to write a simple youtube request to search video with youtube javascript api v3.
This is the source code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
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
function onYouTubeApiLoad() {
// This API key is intended for use only in this lesson.
gapi.client.setApiKey('API_KEY');
search();
}
function search() {
var request = gapi.client.youtube.search.list({
part: 'snippet',
q:'U2'
});
// 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);
}
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="https://apis.google.com/js/client.js?onload=onClientLoad" type="text/javascript"></script>
</head>
<body>
<pre id="response"></pre>
</body>
</html>
When i load this page on google chrome (updated), nothing happens, the page remains blank.
I have request the API Key for browser apps (with referers) and copied in the method gapi.client.setApiKey.
Anyone can help me?
Thanks
Try this example here
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Google AJAX Search API Sample</title>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
// How to search through a YouTube channel aka http://www.youtube.com/members
google.load('search', '1');
function OnLoad() {
// create a search control
var searchControl = new google.search.SearchControl();
// So the results are expanded by default
options = new google.search.SearcherOptions();
options.setExpandMode(google.search.SearchControl.EXPAND_MODE_OPEN);
// Create a video searcher and add it to the control
searchControl.addSearcher(new google.search.VideoSearch(), options);
// Draw the control onto the page
searchControl.draw(document.getElementById("content"));
// Search
searchControl.execute("U2");
}
google.setOnLoadCallback(OnLoad);
</script>
</head>
<body style="font-family: Arial;border: 0 none;">
<div id="content">Loading...</div>
</body>
</html>
When you use <script src="https://apis.google.com/js/client.js?onload=onClientLoad" ..></script>
you have to upload the html file somewhere online or use XAMPP on your PC
To use html for searching YT videos, using Javascript on PC, as I know, we need to use other codings:
1- Use javascript code similar to this for API version 2.0. Except only the existence of API KEY v3.
2- Use the jQuery method "$.get(..)" for the purpose.
See:
http://play-videos.url.ph/v3/search-50-videos.html
For more details see (my post "JAVASCRIPT FOR SEARCHING VIDEOS"):
http://phanhung20.blogspot.com/2015_09_01_archive.html
var maxRes = 50;
function searchQ(){
query = document.getElementById('queryText').value;
email = 'https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=50'+
'&order=viewCount&q='+ query + '&key=****YOUR API3 KEY*****'+
'&callback=myPlan';
var oldsearchS = document.getElementById('searchS');
if(oldsearchS){
oldsearchS.parentNode.removeChild(oldsearchS);
}
var s = document.createElement('script');
s.setAttribute('src', email);
s.setAttribute('id','searchS');
s.setAttribute('type','text/javascript');
document.getElementsByTagName('head')[0].appendChild(s);
}
function myPlan(response){
for (var i=0; i<maxRes;i++){
var videoID=response.items[i].id.videoId;
if(typeof videoID != 'undefined'){
var title=response.items[i].snippet.title;
var links = '<br><img src="http://img.youtube.com/vi/'+ videoID +
'/default.jpg" width="80" height="60">'+
'<br>'+(i+1)+ '. <a href="#" onclick="playVid(\''+ videoID +
'\');return false;">'+ title + '</a><br>';
document.getElementById('list1a').innerHTML += links ;
}
}
}
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
</head>
<body>
<input type="text" value="abba" id="queryText" size="80">
<button type="button" onclick="searchQ()">Search 50 videos</button>
<br><br>
<div id='list1a' style="width:750px;height:300px;overflow:auto;
text-align:left;background-color:#eee;line-height:150%;padding:10px">
</div>
I used the original code that Tom posted, It gave me 403 access permission error. When I went back to my api console & checked my api access time, it was expired. So I recreated the access time for the api. It regenerated new time. And the code worked fine with results.
Simply i must make request from a web server.
Thanks all for your reply
Related
I have a service that I call after every 5 secs to return data from postgres table, now I want this data to be displayed on html document
app.js
const stats=app.service('test_view');
// console.log(stats);
function getstats(){
stats.find().then(response=>{
console.log('data is ',response.data)});};
setInterval(function() {
getstats();
}, 5000);
// console.log(stats);
stats.html
<!DOCTYPE html>
<html>
<head>
<title>Stats</title>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<div id='stats'>
</div>
</body>
</html>
Everything is running fine and I am getting results in console, I am using feather.js now I want these results to be displayed in div tag of html.Please help me in this regard.
You need to call the feathers service from the browser. You can do this a number of different ways (as a REST call, with the feathers client, etc.).
<html lang="en">
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/core-js/2.1.4/core.min.js"></script>
<script src="//unpkg.com/#feathersjs/client#4.0.0-pre.3/dist/feathers.js"></script>
<script src="//unpkg.com/axios/dist/axios.min.js"></script>
<script>
// #feathersjs/client is exposed as the `feathers` global.
const app = feathers();
app.configure(feathers.rest('http://localhost:3000').axios(axios));
app.service('test_view').find();
})
.then(data => {
// do something with data
});
</script>
</head>
<body></body>
</html>
A lot of this depends on what (if anything) you're using for your front-end implementation. This sets up a minimal feathersjs/client using axios for REST, with no authentication, and calls your service (on port 3000) and gets the payload.
To do this every 5 seconds is outside the scope of feathers and up to how you build your web app.
Here is a working example of how you could change the contents of that div when you get data back from your remote call.
// Simulate your remote call... ignore this part.
const stats = {}
stats.find = () => new Promise((resolve, reject) => resolve({
data: 'here is some data ' + new Date().toLocaleTimeString('en-US')
}));
// Div you want to change.
const resultsDiv = document.getElementById('stats');
// Get the data
function getstats () {
stats.find().then(response => {
console.log('data is ', response.data);
// Update the contents of the div with your data.
resultsDiv.innerHTML = response.data;
});
}
setInterval(function() {
getstats();
}, 1000);
<html>
<head>
<title>Stats</title>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<div id='stats'>
</div>
</body>
</html>
I'm trying to use the API of SoundCloud without success, most examples and tutorials on the web are not working.
For the purpose I used this video tutorial. I wish to create on my website a filter by genres.
So first I created an HTML:
<!DOCTYPE html>
<html>
<head>
<script src="//connect.soundcloud.com/sdk.js"></script>
<script src="js/soundcloud.js"></script>
</head>
<body>
<div id="target">
<ul>
<li>punk</li>
<li>rap</li>
<li>rock</li>
</ul>
</div>
</body>
</html>
and than a JavaScript (soundcloud.js):
function playSomeSound(genre){
SC.get('/tracks',{
genres:genre,
bpm:{
from:100
}
}, function(tracks){
var random=Math.floor(Math.random()*49);
SC.oEmbed(tracks[random]).uri,{auto_play:true}, document.getElementById('target')
});
}
window.onload=function(){
SC.initialize({
client_id: 'my_app_id'
});
var menuLinks=document.getElementsByClassName('genre');
for (var i=0; i<menuLinks.lenght;i++){
var menuLink=menuLinks[i];
menuLink.onclick=function(e){
e.preventDefault();
playSomeSound(menuLink.innerHTML);
}
}
};
When I navigate to my website everything is fine, I get no errors from console, however if I click on a genre, it does nothing.
Why it doesn't retrieve songs from SoundCloud?
SoundCloud has changed different things for API use, is there another method?
for (var i=0; i<menuLinks.lenght;i++){ //it should be .length and not lenght
var menuLink=menuLinks[i];
menuLink.onclick=function(e){
e.preventDefault();
playSomeSound(menuLink.innerHTML);
}
}
Also, you misplaced a parenthesis on SC.embed. Here's a working solution: http://jsbin.com/pugegesepu/1/edit
I'm new to using JavaScript so please excuse my bad terminology.
I have a jQuery that is calling an API for a dictionary web service, the whole function works as it should (returning all of the definitions, authors, etc..).
But my problem is that the returned data from the API is coming back in one big block of text and not in a neat format with line spacing between each definition.
If I just search for the URL in a web browser, I get a json response with tidy definitions and spacing.
Here is my search in the service to the API and the data returned.
http://epvpimg.com/MkdEg
Here is the search just using the URL from my code through a web browser (how I think it should look when returned in my web service)
http://epvpimg.com/IWLJf
Has anybody ever seen this problem before or know why, from my code, it is doing so!
Any help would be much appreciated!
$(document).ready(function(){
$('#term').focus(function(){
var full = $("#definition").has("definition").length ? true : false;
if(full === false){
$('#definition').empty();
}
});
var getDefinition = function(){
var word = $('#term').val();
if(word === ''){
$('#definition').html("<h2 class='loading'>We haven't forgotten to validate the form! Please enter a word.</h2>");
}
else {
$('#definition').html("<h2 class='loading'>Your definition is on its way!</h2>");
$.getJSON("http://glosbe.com/gapi/translate?from=eng&dest=eng&format=json&phrase=&pretty=true" +word+ "?callback=?", function(json) {
if (json !== "No definition has been found."){
var reply = JSON.stringify(json,null,"\t");
var n = reply.indexOf("meanings");
var sub = reply.substring(n+8,reply.length);
var subn = sub.indexOf("]");
sub = sub.substring(0,subn);
$('#definition').html('<h2 class="loading">We found you a definition!</h2><h3>'+sub+'</h3>');
}
else {
$.getJSON("http://glosbe.com/gapi/translate?from=eng&dest=eng&format=json&phrase=&pretty=true" + "?callback=?", function(json) {
console.log(json);
$('#definition').html('<h2 class="loading">Nothing found.</h2><img id="thedefinition" src=' + json.definition[0].image.url + ' />');
});
}
});
}
return false;
};
$('#search').click(getDefinition);
$('#term').keyup(function(event){
if(event.keyCode === 13){
getDefinition();
}
});
});
And the HTML
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="author" content="Matthew Hughes">
<meta name="Dictionary" content="A dictionary web service">
<title>Dictionary Web Application</title>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.2.min.js"></script>
<script src="dictionary.js"></script>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div id="container">
<div id="top">
<header>
<h1>Dictionary Application</h1>
</header>
</div>
<div id="app">
<input type="text" placeholder="Enter a word..." id="term" />
<button id="search">Define!</button>
<section id="definition">
</section>
</div>
<footer>
<p>Created by Matthew Hughes</p>
</footer>
</div>
</body>
You're providing a third argument to JSON.stringify, which pretty-prints the result. So sub should have the line breaks you want. The problem is that you're putting it in an HTML document, and HTML automatically merges lines. You can prevent this by using the <pre> tag:
$('#definition').html('<h2 class="loading">We found you a definition!</h2><br><pre>'+sub+'</pre>');
I am trying to get this example as a spotify app, which i will heavily edit. This should be pretty simple for anyone with real experience in the Youtube Data API. I know there are a few solutions about problems similar to this with the google APIs but all of the solutions seem to be specific to the api...
The specific errors I get right now:
Uncaught TypeError: Cannot read property 'prototype' of undefined cb=gapi.loaded_0:6
index.html: This normally just loads main.js but to complete this example, I just stripped the code off of the youtube data api example for search.
<!doctype html>
<html>
<head>
<title>Search</title>
</head>
<body>
<div id="buttons">
<label> <input id="query" value='cats' type="text"/><button id="search-button" disabled onclick="search()">Search</button></label>
</div>
<div id="search-container">
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js" type="text/javascript"></script>
<script src="scripts/auth.js"></script>
<script src="scripts/search.js"></script>
<script src="https://apis.google.com/js/client.js?onload=onLoadCallback"></script>
</body>
</html>
and search.js:
function handleAPILoaded() {
$('#search-button').attr('disabled', false);
}
// Search for a specified string.
function search() {
var q = $('#query').val();
var request = gapi.client.youtube.search.list({
q: q,
part: 'snippet'
});
request.execute(function(response) {
var str = JSON.stringify(response.result);
$('#search-container').html('<pre>' + str + '</pre>');
});
}
Using the Soundcloud JavaScript API, I want to dynamically generate a page of player widgets using track search results. My code is as follows:
<html>
<head>
<script src="http://connect.soundcloud.com/sdk.js"></script>
<script>
function makeDivsFromTracks(tracks,SC)
{
var track;
var permUrl;
var newDiv;
for(var ctr=0;ctr<tracks.length;ctr++)
{
newDiv=document.createElement("div");
newDiv.id="track"+ctr;
track=tracks[ctr];
SC.oEmbed(track.permalink_url,{color:"ff0066"},newDiv);
document.body.appendChild(newDiv);
}
}
</script>
</head>
<body>
<script>
SC.initialize({
client_id: 'MY_CLIENT_ID'
});
SC.get('/tracks',{duration:{to:900000},tags:'hitech',downloadable:true},
function(tracks,SC)
{
makeDivsFromTracks(tracks,SC);
});
</script>
</body>
</html>
When I load this, the SC.oEmbed() call throws an error:
Uncaught TypeError: Cannot call method 'oEmbed' of null
which would seem to indicate that either the divs aren't being generated or the search results aren't being returned, but if I remove the SC.oEmbed() call and replace it with:
newDiv.innerHTML=track.permalink_url;
then I get a nice list of the URLs for my search results.
And if I create a widget using a static div and static URL, e.g.
<body>
<div id="putTheWidgetHere"></div>
<script>
SC.initialize({
client_id: 'MY_CLIENT_ID'
});
SC.oEmbed("http://soundcloud.com/exampleTrack", {color: "ff0066"}, document.getElementById("putTheWidgetHere"));
</script>
</body>
then that works fine as well. So what's the problem with my oEmbed() call with these dynamically created elements?
Solved it. I took out the SC argument from the callback function and makeDivsFromTracks(), and now all the players show up. Not sure exactly why this works--maybe it has to do with the SC object being defined in the SDK script reference, so it's globally available and doesn't need to be passed into functions?
Anyways, working code is:
<html>
<head>
<script src="http://connect.soundcloud.com/sdk.js"></script>
<script>
function makeDivsFromTracks(tracks)
{
var track;
var permUrl;
var newDiv;
for(var ctr=0;ctr<tracks.length;ctr++)
{
newDiv=document.createElement("div");
newDiv.id="track"+ctr;
track=tracks[ctr];
//newDiv.innerHTML=track.permalink_url;
SC.oEmbed(track.permalink_url,{color:"ff0066"},newDiv);
document.body.appendChild(newDiv);
}
}
</script>
</head>
<body>
<script>
SC.initialize({
client_id: 'MY_CLIENT_ID'
});
SC.get('/tracks',{duration:{from:180000,to:900000},tags:'hitech',downloadable:true},function
(tracks){makeDivsFromTracks(tracks);});
</script>
</body>
</html>