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>');
});
}
Related
I am trying to set up a simple search function with Google Books API. When I have my search parameter set as a simple preset string, it works fine. But when I attempt to make it take user input for the search parameter using document.getElementByID, it suddenly no longer works. I am uncertain of what could be going wrong,
<!DOCTYPE html>
<html>
<head>
<title>Google Books Search</title>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
</head>
<body>
<h1 id="title"></h1>
<h2>Searched "jquery"; Total results: <span id="total"></span>
<p>The results from 30 to 45 are displayed here (15 per page; results page #3).</p></h2>
<div id="results" style="display: flex; flex-wrap: wrap;"></div>
<input id="searchterm" type="text" placeholder="Search..." >
<button onclick="booksearch()">Search</button>
<script>
$(function booksearch(){
let term = "document.getElementById("searchterm").value;"
var parameter="?q="+term+"&startIndex=30&maxResults=15";
var service_point="https://www.googleapis.com/books/v1/volumes/"+parameter;
$.getJSON(service_point, function (json)
{
console.log(json);
var total=json.totalItems;
$("#total").text(total);
var resultHTML="";
for (i in json.items)
{
var booktitle=json.items[i].volumeInfo.title;
var bookid=json.items[i].id;
var cover="";
if (json.items[i].volumeInfo.imageLinks != null)
cover=json.items[i].volumeInfo.imageLinks.smallThumbnail;
resultHTML+="<div class='bookdiv'>";
resultHTML+="<img src='"+cover+"' style='float: left' />";
resultHTML+="<a href='bookinfo.html?id="+bookid+"'>"+booktitle+"</a>";
resultHTML+="</div>";
}
$("#results").html(resultHTML);
$(".bookdiv").css("width", "300px");
});
});
</script>
</body>
</html>
You should not put your "document.getElementById("searchterm").value;" within quotes otherwise it will just be a string.
Use let term = document.getElementById("searchterm").value; instead.
On another note: I would suggest you use fetch() together with URLSearchParams which will do the "heavy-lifting" (i.e. URL-encoding, addition of ? and & etc.) for you instead of concatenating those strings yourself (and you will use some modern JavaScript).
See this SO answer for an example.
I am kind of new to writing code and using API's. I am not entirely sure why my program is not working the way I would like it to.
What I want this to do is provide the search results in the console before I can move onto what I would like it to do next; however, I don't think anything is being searched.
According to this: https://developers.google.com/youtube/v3/docs/search/list#http-request, the only required parameter is "part," so I think I did everything right? Probably not though, because from what I can tell, nothing is being searched when I try to search for a term.
Here is my code:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<section>
<form id="search-term">
<p>Enter Name:<br/>
<input id="query" type="text" name="Name"/><br/>
<hr/>
<input type="button" value="Enter here"/>
</p>
<div id="search-results">
</div>
</form>
</section>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="js/script.js"></script>
</body>
</html>
JavaScript:
$(document).ready(function(){
$('#search-term').submit(function(event){
event.preventDefault();
var searchTerm = $('#query').val();
getRequest(searchTerm);
});
function getRequest(searchTerm){
var params = {
"q": "searchTerm",
"part": 'snippet',
"type": 'video',
"key": 'I was advised to keep my key private, so I edited this part out'
}
url = 'https://www.googleapis.com/youtube/v3/search';
$.getJSON(url, params, function(data){
showResults(data.items);
})
}
function showResults(results){
var html = "";
$.each(results, function(index,value){
html += '<p>' + value.snippet.thumbnails.high.url + '</p>' + '<p>' + 'https://www.youtube.com/watch?v=' + value.id.videoId + '</p>' + '<hr/>';
console.log(value.snippet.thumbnails.high.url);
console.log(value);
})
$('#search-results').html(html);
}
})
You probably want data.items instead of data.search
I don't see any mention of a 'search' parameter under the "Response" section listed in their documentation. See the response properties here: https://developers.google.com/youtube/v3/docs/search/list#response
Therefore, you can probably see some output if you console.log(data); instead of data.search
I recommend you check out Google's Javascript API Client Library. It might not be the best solution for you, but it's worth a try. Download on GitHub
Example using gapi.client.youtube.search.list:
// After the API loads, call a function to enable the search box.
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>');
});
}
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'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
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>