Retrieving Videos from Youtube and searching/categorizing - javascript

Currently I am trying to pull videos from a youtube channel with youtube api and then using javascript to search and categorize it. I can get a search to work on an html table, but can't get it to work on the table I'm creating through the api.
My current html code is just basically this:
<script src="js/jquery-1.11.3.min.js"></script>
<script src="js/script.js"></script>
</head>
<body>
<div id="container">
<h1> RBx Youtube Videos </h1>
<input type="text" id="search" placeholder="Type to search">
<table id="results"> </table>
</div>
</body>
The videos are retrieved here:
$(document).ready(function(){
$.get(
"https://www.googleapis.com/youtube/v3/channels",{
part: "contentDetails",
forUsername: channelName,
key: pkey},
function(data){
$.each(data.items, function(i, item){
console.log(item);
pid = item.contentDetails.relatedPlaylists.uploads;
getVids(pid);
})
}
);
function getVids(pid){
$.get(
"https://www.googleapis.com/youtube/v3/playlistItems",{
part: "snippet",
maxResults: 50,
playlistId: pid,
key: pkey},
function(data){
var output;
$.each(data.items, function(i, item){
console.log(item);
videoTitle = item.snippet.title;
videoId = item.snippet.resourceId.videoId;
videoDescription=item.snippet.description;
output = '<tr><td><img src="http://img.youtube.com/vi/'+videoId+'/1.jpg"></img></td><td>'+videoTitle+'</td></tr><tr><td colspan="2" align="right">'+videoDescription+'<hr>';
//output = '<tr><td>'+videoTitle+'</td></tr>';
//Append to results listStyleType
$('#results').append(output);
})
}
);
}
}

I will assume that the values of variables you use in your output string are valid. Please pay attention to the correctness of your HTML syntax in the output string. The <img> element must not have a closing tag as it is an empty element, and you should end your string with </td></tr>:
output = '<tr><td><img src="http://img.youtube.com/vi/'+videoId+'/1.jpg"></td><td>'+videoTitle+'</td></tr><tr><td colspan="2" align="right">'+videoDescription+'<hr></td></tr>';
In general, this way of generating HTML is risky and error-prone. You should always validate, clean up, or escape all variables used in the output. Perhaps it can be of help to take a look at the <template> element introduced in HTML5, and make use of it in this kind of situations. You can check this example using table rows.

Related

Get certain json values and displaying on html page

I made a small webpage that asks the user to enter the name of an actor and I was hoping to then display all of the movies the actor had appeared in. For my question, I've hard coded the api URL for the actor (Bradley Cooper).
How do I grab all of the movie titles, the release year, movie overview, and the movie poster value and display them all on the page? Right now, I'm only able to display one movie and for some strange reason, it's not the first movie mentioned in the json file.
I think I need to get the json data into an array but I'm not sure how to do that and I'm not sure how to then display more than one result on the page.
I appreciate any help and guidance you can provide.
<!DOCTYPE html>
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body onload="search_actor()">
<script>
function search_actor() {
$.getJSON({
url: 'https://api.themoviedb.org/3/person/51329/movie_credits?api_key=f1d314280284e94ff7d1feeed7d44fdf',
dataType: 'json',
type: 'get',
cache: false,
success: function(data) {
$(data.cast).each(function(index, moviedata) {
// Movie Title
document.getElementById("movietitle").innerHTML = moviedata.title;
// Release Year
document.getElementById("releaseyear").innerHTML = moviedata.release_date.substr(0, 4);
// Movie Overview
document.getElementById("movieoverview").innerHTML = moviedata.overview;
// Movie Poster
var fullmovieposterpath = '<img src=https://image.tmdb.org/t/p/w500/' + moviedata.poster_path + ' width="20%" height="20%">';
document.getElementById("displaymovieposter").innerHTML = fullmovieposterpath;
});
}
});
}
</script>
<div id="movietitle"></div>
<div id="releaseyear"></div>
<div id="movieoverview"></div>
<div id="displaymovieposter"></div>
</body>
</html>
In your code you have single only one container to display the movie items.You need to loop over the response and dynamically create the movie cards.Also use css grid system to have more control over the movie card and their placement.
$.getJSON({
url: 'https://api.themoviedb.org/3/person/51329/movie_credits?api_key=f1d314280284e94ff7d1feeed7d44fdf',
dataType: 'json',
type: 'get',
cache: false,
success: function (data) {
console.log(data)
let k = '';
data.cast.forEach(function (item) {
//Using template literal to create a movie card
k += `<div class='movie-card'>
<div>${item.original_title}</div>
<div><img src = 'https://image.tmdb.org/t/p/w500/${item.poster_path}'></div>
<div><span>${item.release_date}</span></div>
<div class='movie-desc'>${item.overview}</div>
</div>`
})
$('.movie-conatiner').append(k)
}
});
See complete working copy here at stackblitz
Currently, you are displaying data in single division, so data is getting overwritten.
Instead you need to dynamically build division in for each statement and then assign the entire data in home page.
Also create only single div in html part with id="main"
Below is the updated code with above change. Please give proper CSS to the divisions.
Code after getting json response
divcnt=1;
divdata="";
$(data.cast).each(function(index, moviedata) {
var fullmovieposterpath = '<img src=https://image.tmdb.org/t/p/w500/' + moviedata.poster_path + ' width="20%" height="20%">';
divdata += '<div id="test'+ divcnt +'"><div id="movietitle'+ divcnt +'">'+moviedata.title+'</div><div id="releaseyear'+ divcnt +'">'+moviedata.release_date.substr(0, 4)+'</div><div id="movieoverview'+ divcnt +'">'+moviedata.overview+'</div><div id="displaymovieposter'+ divcnt +'">'+fullmovieposterpath+'</div></div>';
});
document.getElementById("main").innerHTML = divdata;

Generating a List and Subsequent Pages from JSON

In my project, I have a JSON file. I display the data that is parsed inside a list (ul) under a div with the class, "inner", and show only the name and cost of each product that you can see in my JSON.
{
"product": [
{
"name": "samsung galaxy",
"image": "https://rukminim1.flixcart.com/image/832/832/mobile/v/z/x/samsung-galaxy-on-nxt-sm-g610fzdgins-original-imaenkzvmnyf7sby.jpeg?q=70",
"cost": "RS.10,000",
"detail": "Flaunt your style with the Samsung Galaxy On Nxt. Featuring a drool-worthy body and impressive features, this smartphone is built to perform. Talk to your mom, chat with your friends, browse the Internet - stay connected the way that suits you best - this smartphone is powerful enough to keep up with your busy lifestyle."
}
]
}
When I click on the first product (first list item), I want to show the detail (value detail) of this product in another page from that same JSON object; when I click on the second product, I want that to show in a different page too, but also from that same object.
Here's my HTML:
<html>
<head>
<title>jquery</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$.ajax({
url: 'http://sonsofthunderstudio.in/jj/product.json',
dataType: 'jsonp',
jsonpCallback: 'jsonCallback',
type: 'get',
crossDomain : true,
cache: false,
success: function(data) {
$(data.product).each(function(index, value) {
console.log(value);
$( ".inner" ).append("<li>"+value.name+"<img src='" + value.image + "' width='50px' height='50px' / >"+value.cost+"</li>");
});
}
});
</script>
<div class="inner">
</div>
</body>
</html>
Where can I go from here?
When you want to show details of your product, You have to create a "ProductList.html" to show your product list, and create a "ProductDetail.html" to show product detail based on selected product.
when user click on a product, You have to pass the selected product to "ProductDetail.html" via url and get it in that page.
the 2 "encodeURIComponenet()" and "decodeURIComponent()" are javascript defined functions to make this action encoded and safe.
To achieve this, You have to append a "Link"(A Tag) to $(".inner"):
$(".inner").append("<a href='#'>"+value.name+"</a>");
in code above, you create a link, you pass the Product ID to destination page and In codes below, You set the "href" attribute for the link:
var _SelectedProduct = "ID=" + ProductID;
var _EncodeID = encodeURIComponenet(_SelectedProduct);
document.getElementById("YourLink").href = "ProductDetail.html?" + _EncodeID;
with these codes, when user click on a product, he will be redirected to "ProductDetail.html" with the selected product ID. You can get this ID in Your ProductDetail.js:
var _DecodeURL = decodeURIComponent(window.location);
var ID = _DecodeURL.split("=");
var _ProductID = ID[1];
with these codes, you split the passed url base on ("="), which means you will get the passed Product ID.(_ProductID).
and :
for(i=0;i<=product.lenght; i++){
if(product[i].ID == _ProductID){ ... }
}
You can add onclick event on li and call a function which will store the particular detail in localStorage.
On the next page you can access detail from localStorage and display it.
//--[Appending in your code]--
.
.
.
$(data.product).each(function(index, value) {
console.log(value);
$( ".inner" ).append("<li onclick='foo('"+value.detail+"')'>"+value.name+"<img src='" + value.image + "' width='50px' height='50px' / >"+value.cost+"</li>");
});
<script type="text/javascript">
function foo(detail)
{
localStorage.setItem("DETAIL",detail);
}
</script>
//--[On second page]--
<head>
<script type="text/javascript">
var detail = localStorage.getItem("DETAIL");
$("#details").html(detail);
</script>
</head>
<body>
<div id="details"></div>
</body>
When you append data first you need to do is to add an Identifier because you need to differentiate the elements and you need to put onClick to each element that you will append you can put it like this: '<li id="'+ index +'" onClick="clicklist(this)">'+ value.name (...) +'</li>'
The second thing you need to declare is a function called clicklist or something with the param element.
function clicklist(element) { }
Fill it with the code I will explain now:
You can access to your list data through the element with your jQuery functions. So first you can get id with var id = $(element).attr('id'); then you can find your list elements and get it value with var itemname = $(element).find("typeofelement.class").attr('value'); etc...
When you get all data in your list you need to open a new window with the params you get in the function. Then use this code:
//Add all the values you need in the other html (id and values) So repeat this line:
sessionStorage.setItem("ID", id);
//Open the window
window.open("yourother.html","_blank");
This is the simple way.

javascript that can access element declared in a variable

List item
i want a javascript that can access the button elements inside
the
dot.append() function. so that when i clicked the button i
get the value of that button.
below is a piece of code that have been working on this morning.
i appreciate any support or hint from anyone.Thank you in
advance.
further more i am also new in youtube data api.
function main_search(){
$("form").on("submit",function(e){
e.preventDefault();
//after that we prepare the request
var myRequest = gapi.client.youtube.search.list({
part: 'snippet',
q: encodeURIComponent($("#query").val()).replace(/%20/g, "+"),
maxResults :5,
type : 'video'
});
// then we execute the request
myRequest.execute(function(response){
var results = response.result;
$.each(results.items, function(index,item){
$("#results").append('<li>'+item.id.videoId+" "+item.snippet.title+"
"+item.snippet.channelTitle+" "+item.snippet.description+"
"+item.snippet.publishedAt+" "+'<img
src="'+item.snippet.thumbnails.high.url+'">'+'<button
class="class_btns" value="'+item.id.videoId+'">'+'get video url
'+'</buttons>'+'</li>'+"<br>");
});
});
});
}
function loadAPI(){
gapi.client.setApiKey("AIzaSyC1CJHONRDvyfSS3xAOG9SfW_VCXMoLK5Y");
gapi.client.load("youtube","v3", function(){
//my youtube api is read
main_search();
});
}
<form action="#">
<input type="search" id="search_string" placeholder="Your string
goes
here...."></input>
<input type="submit" name="search-btn" id="search_btn" value="search">
</input>
</form>
<ul id="result_box"></ul>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1
/jquery.min.js"></script>
<script src="search.js"></script>
Just divide your statement into two lines so that you can access the element later:
var element = document.createElement('<li>'+item.id.videoId+" "+item.snippet.title+"
"+item.snippet.channelTitle+" "+item.snippet.description+"
"+item.snippet.publishedAt+" "+'<img
src="'+item.snippet.thumbnails.high.url+'">'+'<button
class="class_btns" value="'+item.id.videoId+'">'+'get video url
'+'</buttons>'+'</li>'+"<br>");
$("#results").append(element);
Or if you want a jQuery object instead:
var element = $('<li>'+item.id.videoId+" "+item.snippet.title+"
"+item.snippet.channelTitle+" "+item.snippet.description+"
"+item.snippet.publishedAt+" "+'<img
src="'+item.snippet.thumbnails.high.url+'">'+'<button
class="class_btns" value="'+item.id.videoId+'">'+'get video url
'+'</buttons>'+'</li>'+"<br>");
You can then access whatever you want from the element variable.
Alternatively you can just grab the button later using the class if you keep your current code:
var button = $('.class_btns');

Get Item Count for a Specific View

Is there a piece of jQuery or JavaScript that I can run that will allow me to create a Content Editor Web Part that has "This is the number of list items: XYZed."
I've tried this but it is not working:
http://www.martinhatch.com/2010/09/how-to-achieve-count-on-large.html
The one I tried was the 4'th attempt. If someone could help me that would be fantastic.
try these solutions/posts in the given order.
https://sharepoint.stackexchange.com/questions/5477/getting-a-count-of-list-items-in-a-list-via-ecmascript
https://sharepoint.stackexchange.com/questions/18050/how-do-i-get-the-number-of-items-in-a-list
http://www.codeproject.com/Questions/266281/jQUERY-TO-GET-COUNT-OF-TOTAL-ITEMS-EXISTED-IN-SP-L
It worked for me. All I had to do was create the grouped view and put the url into the code. Tho I used quotes
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//////////
// you will need to change this URL
var url = "http://sppos/Lists/Statistics/Grouped.aspx";
//////////
var groupings = [];
$.get(url, function(data) {
$(data).find("tbody[id^=titl][groupString] > tr > td").each(
function(index, value){
groupings.push($(this).text());
}
);
$("#placeholder").append("<ul></ul>");
$.each(groupings, function(index, value){
$("#placeholder ul").append("<li>" + value + "</li>")
});
});
});
</script>
<div id="placeholder"></div>
After testing, no quotes doesn't work, which may be the cause of some grief

Change javascript onclick event to jquery click and still pass parameters

I think I may be missing something or haven't grasped a fundamental of jQuery. I have searched for hours but yet to find an answer to my question.
I've got an old website that I'm upgrading to use jQuery and many of the links call a JavaScript onClick call that passes multiple parameters, as per the example below:
View Details
The problem is that I've updated the old displayData function with various jQuery code and the displayData function is within the
$(document).ready(function() {
});
code, and this seems to prevent the function displayData being called using the onClick as it says object expected. I've moved the displayData function out from the $(document).ready() but by doing so, this has prevented references to other functions within the $(document).ready() code being referenced.
A cut down example of what I have is below:
<script>
$(document).ready(function() {
function displayData(title, isbn, dt, price) {
// there's a call to jQuery AJAX here
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "WebServices/BookService.asmx/GetBookReviews",
data: "{isbn: '" + isbn + "'}",
dataType: "json",
success: function(msg) {
DisplayReviews(msg.d);
}
});
return false;
}
function DisplayReviews(data) {
// data normally formatted here and passed to formattedData variable
var formattedData = FormatData(data);
$('#reviewScreen').html(formattedData);
}
function FormatData(data) {
// function reformats data... code removed for space..
return data;
}
});
</script>
<table>
<tr><td>View Reviews</td><td>Book Title</td></tr>
<tr><td>View Reviews</td><td>Book Title 2</td></tr>
</table>
What I'd like to do is to be able to remove the onclick="displayData();" within the link and instead us a jQuery click reference, something like
$('a.reviewLink').click(function() {
displayData(parameters go here....);
});
I just don't know how I'd pass the parameters to the function from the link as they would not longer be in the HTML onclick attribute.
If I continue to use the onclick attribute in the link, and move the displayData(params) out of the $(document).ready() code block, it works fine, but the moment I try and reference any of the other functions within the $(document).ready() code block I get the dreaded object expected error with the other functions such as DisplayReviews(param).
I don't know if this makes any sense.... sorry if it's confusing, I'm not the worlds best programmer and don't know all the terminology necessarily, so have tried as best I can to explain. I hope you can help.
Many thanks
The init code should go into the .ready(), not your library functions, those can be defined in a seperate .js file.
<script src="yourFunctions.js"></script>
<script>
$(document).ready(function(){
$('a.reviewLink').click(function() {
displayData(parameters go here....); // in yourFunctions.js
});
});
</script>
An alternative to passing inline parameters without using inline javascript, is to use HTML5's 'data-' attribute on tags. You can use it in xhtml, html etc as well and it just works.
html:
<div data-name="Jack" data-lastname="black">My name is</div>
jquery:
$('div').click(function(){
alert($(this).attr('data-name') + ' ' + $(this).attr('data-lastname'));
});
Note: You HAVE to use either jQuery's .attr() or native .getAttribute() method to retreive 'data-' values.
I use 'data-' myself all the time.
As pointed out by Skilldrick, displayData doesn't need to be defined inside your document ready wrapper (and probably shouldn't be).
You are correct in wanting to use the jQuery click event assignment rather than onClick - it makes your code easier to read, and is required by the principle of Unobtrusive Javascript.
As for those parameters that you want to pass, there are a few ways to go about the task. If you are not concerned with XHTML compliance, you could simply put some custom attributes on your link and then access them from your script. For example:
View Details
And then in your click event:
$('a.reviewLink').click(function() {
var booktitle = $(this).attr('booktitle');
var isbn = $(this).attr('isbn');
var pubdate = $(this).attr('pubdate');
var price = $(this).attr('price');
displayData(booktitle, isbn, pubdate, price);
});
I'm sure someone on here will decry that method as the darkest evil, but it has worked well for me in the past. Alternatively, you could follow each link with a hidden set of data, like so:
View Details
<ul class="book-data">
<li class="book-title">Book Title</li>
<li class="book-isbn">ISBN</li>
<li class="book-pubdate">Publish Date</li>
<li class="book-price">Price</li>
</ul>
Create a CSS rule to hide the data list: .book-data { display: none; }, and then in your click event:
$('a.reviewLink').click(function() {
var $bookData = $(this).next('.book-data');
var booktitle = $bookData.children('.book-title').text();
var isbn = $bookData.children('.book-isbn').text();
var pubdate = $bookData.children('.book-pubdate').text();
var price = $bookData.children('.book-price').text();
displayData(booktitle, isbn, pubdate, price);
});
There are lots of ways to accomplish your task, but those are the two that spring most quickly to mind.
I worked this up, so even though the question is answered, someone else might find it helpful.
http://jsbin.com/axidu3
HTML
<table border="0" cellspacing="5" cellpadding="5">
<tr>
<td>
View Reviews
<div class="displayData">
<span class="title">Book Title 2</span>
<span class="isbn">516AHGN1515</span>
<span class="pubdata">1999-05-08</span>
<span class="price">$25.00</span>
</div>
</td>
<td>Book Title 2</td>
</tr>
</table>
JavaScript
<script type="text/javascript" charset="utf-8">
jQuery(".reviewLink").click(function() {
var title = jQuery(".title", this.parent).text();
var isbn = jQuery(".isbn", this.parent).text();
var pubdata = jQuery(".pubdata", this.parent).text();
var price = jQuery(".price", this.parent).text();
displayData(title, isbn, pubdata, price);
});
function displayData(title, isbn, pubdata, price) {
alert(title +" "+ isbn +" "+ pubdata +" "+ price);
}
</script>
CSS
<style type="text/css" media="screen">
.displayData {
display: none;
}
</style>

Categories