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>');
});
}
Related
I would label my coding skills as intermediate thus what I am asking may or may not be simple or obvious (I wouldn't know the difference). Also I sincerely thank any and everyone who gives this even an ounce of attention.
My objective is to grab raw song metadata from another server (in which I am a client of) via the jsonp and ajax method. Once I successfully obtain the metadata (Artist, Title & album), I then would like to display it in my website’s page title (please see pics below).
The reason I would like to do this is because from what I could gather via an extensive and worn out research, it seems that most Bluetooth Audio devices are reading the metadata from the page title (browser tab):
Google Music playing in browser
BT Audio player
What I would love to do seems like it should be simple to do, yet I cannot figure away to display "Artist, Title and Album" in my browser like Spotify, Youtube or Google Music does.
My code below is able to pull the raw data, convert it using jsonp and I can successfully push only ONE element from the raw data (IE 'title') by placing it as an ID element. However, how can I push all three (Artist, Title & Album) to the page title?
<!DOCTYPE html>
<html
lang=en
dir="ltr"
class="mobile-web-player"
>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
function update(metadataObj) {
if (metadataObj && metadataObj.m_Item2) {
var title = document.getElementById('title');
title.innerHTML = metadataObj.m_Item2.Title;
var artist = document.getElementById('artist');
artist.innerHTML = 'by ' + metadataObj.m_Item2.Artist;
var album = document.getElementById('album');
album.innerHTML = metadataObj.m_Item2.Album + ' ';
}
}
</script>
<script type="text/javascript">
var stationID = 'X123';
var apiToken = 'X12345';
// refresh MetaData every 5 seconds
function fetchMetadata(stationID, apiToken) {
$.ajax({
type: 'get',
cache: false,
url: "https://listen.samcloud.com/webapi/station/X123/history/npe?token=X12345&callback=update&format=json",
//async: true,
datatype: 'jsonp',
});
}
fetchMetadata(stationID, apiToken);
window.setInterval(function() {
fetchMetadata(stationID, apiToken);
}, 5000);
</script>
<!-- I can successfully send the song's title to my page title via <title id> method -->
<title id="title">My Radio Station</title>
</head>
<body>
</body>
</html>
In your update() function you can call document.title to set the new tab title instead of setting the <title> tag. For example:
function update(metadataObj) {
if (metadataObj && metadataObj.m_Item2) {
var title = document.getElementById('title');
var artist = document.getElementById('artist');
var album = document.getElementById('album');
// If you are using es6
document.title = `Playing ${title} from ${artist} - ${album}`;
// If not using es6
// document.title = 'Playing '+ title + ' from '+ artist +' - album';
}
}
You could change your update function to the following to write Artist, Title, and Album to the web pages title.
function update(metadataObj) {
if (metadataObj && metadataObj.m_Item2) {
var title = document.getElementById('title');
title.innerHTML = metadataObj.m_Item2.Title + ' ' + metadataObj.m_Item2.Album + ' ' + metadataObj.m_Item2.Artist;
}
}
So i'm back here again trying to figure out how to use HTML correct and can't get it to work correctly after been trying many hours with this.
Anyways, i'm trying to make so the picture and youtube trailer should be shown in the HTML and what I search for is something like this.
Right now im searching to make something like the picture but to get picture to be shown and a player with the trailer
so basically I want it to look similar like picture number one and I have come so far:
<!DOCTYPE html>
<html>
<head>
<title>Movies</title>
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
function callAjax(input)
{
var url = "http://localhost:1337/search/" + input;
$.ajax({
type:'GET',
url: url,
success: function(data)
{
console.log('SUCCESS');
$('#title').html("Title: " + data.title);
$('#release').html("Release: " + data.release);
$('#vote').html("Vote: " + data.vote);
$('#overview').html("Overview: " + data.overview);
$('#poster').html("Poster: " + data.poster);
},
error: function(request, status, err)
{
console.log('ERROR');
}
});
}
$(document).ready(function(){
$('#get-json').on('click', function(e){
e.preventDefault();
var input = $('#data').val().trim();
callAjax(input);
});
});
</script>
<body>
<center>
<div>
<input type="text" id="data" name="data" size="15" maxlength="120" />
<button type="submit" value="search" id="get-json">Search</button>
</div>
</center>
<section>
<div id="json-output"></div>
<div id="title"></div>
<div id="release"></div>
<div id="vote"></div>
<div id="overview"></div>
<div id="poster" img src="data.poster" style="width:104px;height:142px;"></div>
</section>
</body>
</html>
Also forgot to say that i'm very new at this, never done HTML really before and been trying to figure out this for a while without a result :(
You need to create placeholders for your JSON elements. At first write without that JSON a sample of HTML page that will look like you want. That page should have elements (for example div) for title, release and so on. Those elements should have its class or ids to be addressed (as it is already with <div id="json-output">)
You do not have to stringify your JSON. It is better to work JSON, since you can address its elements. For example, to set value into specific placeholder element you can use:
$('#title').html(data.title);
$('#relese').html(data.release);
$('#vote').html(data.vote);
JSON.stringify will return the contents of a JSON object as a string. It will not parse your JSON object and return HTML.
You can create a simple list like this:
function(data){
var $list = $('<ul>');
$list.append('<li>Title: ' + data.title + '</li>');
$list.append('<li>Release: ' + data.release + '</li>');
$list.append('<li>Vote: ' + data.vote + '</li>');
$list.append('<li>Overview: ' + data.overview + '</li>');
$('#json-output').html($list);
}
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>');
});
}
I'm new in Jquery, I would like to have Jquery code to get the current page url and if the url contains certain string then load remote element.
example:
i have the page urls like this:
"http://......./Country/AU/result-search-to-buy"
"http://......./Country/CA/result-search-to-buy"
"http://......./Country/UK/result-search-to-buy"
the part "/Country/AU" is what I need to determine which page element I should load in, then if "AU" I load from "/state-loader.html .state-AU", if "CA" I load from "/state-loader.html .state-CA"
I have a builtin module "{module_pageaddress}" to get the value of the current page url, I just dont know the Jquery logic to let it work.
I expect something like this:
if {module_pageaddress} contains "/Country/AU/"
$('#MyDiv').load('state-loader.html .state-AU');
if {module_pageaddress} contains "/Country/CA/"
$('#MyDiv').load('state-loader.html .state-CA');
please help and many thanks.
Here is some code:
<!DOCTYPE html>
<html>
<head>
<title>jQuery test page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function loadContent(elementSelector, sourceURL) {
$(""+elementSelector+"").load(""+sourceURL+"");
}
function stateURL() {
var startOfResult = '../../state-loader.html #state-';
var match = (/(?:\/Country\/)(AU|US|CA|UK)(?:\/)/).exec(window.location.pathname);
if (match) {
return startOfResult + match[1];
} else {
return startOfResult + 'AU';
}
}
</script>
</head>
<body>
Link 1
<div id="content">content will be loaded here</div>
</body>
</html>
And the file to load the different content for the states:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="state-US">Go USA!</div>
<div id="state-CA">Go Canada!</div>
<div id="state-AU">Go Australia!</div>
<div id="state-UK">Go United Kingdom!</div>
</body>
</html>
See it work here:
http://www.quirkscode.com/flat/forumPosts/loadElementContents/Country/US/loadElementContents.html
Replace .../US/... with .../AU/..., etc. to see how it behaves.
Original post where I got the ideas/original code:
http://frinity.blogspot.com/2008/06/load-remote-content-into-div-element.html
You can try
var countryCode = ... // parse the country code from your module
$('#yourDiv').load('state-loader.html .state-' + countryCode);
See more examples of .load() here.
As far as pulling the url path you can do the following
var path_raw = document.location.path,
path_array = path_raw.split("/");
Then, you could do something like this:
$.ajax({
url: "./remote_data.php?country=" + path_array[0] + "&state=" + path_array[1],
type: "GET",
dataType: "JSON",
cache: false,
success: function(data){
// update all your elements on the page with the data you just grabbed
}
});
Use my one line javascript function for getting an array of the URL segments: http://joshkoberstein.com/blog/2012/09/get-url-segments-with-javascript
Then, define the variable $countrySegment to be the segment number that the country code is in.
For example:
/segment1/segment2/CA/
(country code would be segment 3)
Then, check if the 3rd array index is set and if said index is either 'CA' or 'AU'. If so, proceed with the load, substituting in the country-code segment into the .html filename
function getSegments(){
return location.pathname.split('/').filter(function(e){return e});
}
//set what segment the country code is in
$countrySegment = 3;
//get the segments
$segments = getSegments();
//check if segment is set
//and if segment is either 'AU' or 'CA'
if(typeof $segments[$countrySegment-1] !==undefined && ($segments[$countrySegment-1] == 'AU' || $segments[$countrySegment-1] == 'CA')){
$countryCode = $segments[$countrySegment-1];
$('#target').load('state-loader.html .state-' + $countryCode);
}
var result= window.location.pathname.match(/\/Country\/([A-Z]+)\//);
if(result){
$('#MyDiv').load('state-loader.html .state-' + result[1]);
}