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;
Related
I have a webpage in which I want to display the articles headlines that I am fetching from NewYork Time API, I am using nodejs as well, but the problem is that my articles gets printed below the end of html, although it should be printed inside like the "SAMPLE TEXT" is getting printed, is there a way in which I can print it inside?
http://imgur.com/sNmbqeN
<div class="card">
<div class="header">
<h3 class="title"><center><b>Chronicle</b></center></h3>
</div>
<body>
<p id="headline">SAMPLE TEXT</p>
<script src="//cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.9/p5.js"></script>
<script>
var url = "https://api.nytimes.com/svc/search/v2/articlesearch.json";
url += '?' + $.param({
'api-key': "removed",
'q': "Trump"
});
$.ajax({
url: url,
method: 'GET',
}).done(function(result) {
var articles = result.response.docs;
for (var i=0; i<articles.length;i++)
{
document.createElement('div');
document.createElement("H1");
var h = document.createElement("H1");
var t = document.createTextNode(articles[i].headline.main);
h.appendChild(t);
document.body.appendChild(h);
}
}).fail(function(err) {
throw err;
});
</script>
</body>
Your articles are being inserted at the end of the page because that is what you are asking javascript to do in your "document.body.appendchild" line. If you want your retrieved articles to go in a specific div or p tag, do something like this:
<p id="articles">Articles listed below:</p>
<script>
var newArticle = document.createElement("div");
var h = document.createElement("H1");
h.appendChild(document.createTextNode("Header"));
newArticle.appendChild(h);
var t = document.createTextNode("New article text");
newArticle.appendChild(t);
document.getElementById("articles").appendChild(newArticle);
</script>
I can't test with your original code using the NYT api but you should be able to see how it's done at least with the code above.
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.
I'm trying to add a review snippet to a webpage after retrieving the corresponding data-id from the database. Unfortunatly the snippet doesn't work properly if I add the snippet like shown below. The snippet works fine if it is hardcoded in html but not if I add it in javascript or if I put the snippet without a data-id and then try to append the data-id attribute with the correct id.
I've tried loading my ajax call to the database in a script next to the div's location to then simply use document.write() but without success. The snippet in use is a review snippet from Mobials.
Help is greatly appreciated.
<div id="mobials"> </div>
<script type="text/javascript" src="//api.mobials.com/assets/js/api/v1.js"></script>
<script type="text/javascript" src="https://mobials.com/assets/js/api/review.min.js"></script>
function Submit() {
if (validateInputs()) {
$.ajax({
type: "GET",
url: "#ViewBag.urlApi" +"LocationDetails?zipcode=" + $("#ZipCodeLoc").val() + "&format=JSON&authoriazation={"+"#ViewBag.ApiKey"+"}",
dataType: "jsonp",
traditional: true,
success: function (data) {
$("#events").empty();
$("#logos").empty();
$("#openingHours").empty();
locationDetails = JSON.parse(data);
//Customer Reviews
var isMobial = false;
$.each(locationDetails.Reviews, function (key, value) {
if(key == "Type" && value == 1){
isMobial = true;
$("#consumerAffairs").hide();
}
if(key == "ReviewCode" && isMobial){
var mob = document.getElementById("mobials");
mob.innerHTML += '<div class="mobials-root" data-id="'+value.reviewcode+'" data-language="en" data-type="badge" data-size="200"></div>';
}
});
}};
}
}
EDIT: This line in my .html:
<div class="mobials-root" data-id="someId" data-language="en" data-type="badge" data-size="200"></div>
Looks like this when loaded:
<div class="mobials-root" data-id="someId" data-language="en" data-type="badge" data-size="200" data-tracker="1" id="mobial-root-1"><img src="https://s3.amazonaws.com/mobials.com/api/badges/read_reviews/en/174_174_4.7_70.png"></div>
You can't use document.write() with ajax calls.
document.write() will work "as expected" only as long as the document is open. As soon as the browser recognizes that the document is loaded completely, the document is closed.
Subsequent calls to document.write() will replace the document rather than append to it.
Edit: but looking at your code, I don't see document.write() at all.
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.
Once again I humbly come before you with bruises upon my head from beating my head against a wall...
I have been trying to learn as I go in figuring out how to populate a jQuery EasyUI accordion from a php/MySQL query. I believe that I am now getting the data back to the webpage correctly, but I am unable to figure out how to parse and format this to be displayed as the content on the page. What I am attempting to achieve is basically an accordion to display the contact history with each correspondence with an individual as an accordion item. Here is a sample of the output from the PHP query.
{"rows":[{"phone":"5554072634","contact_dt":"2014-01-27 22:51:37","method":"Email","who":"Scott","note":""},{"phone":"5554072634","contact_dt":"2014-01-27 23:08:49","method":"Spoke","who":"Scott","note":"Called back and she is not interested."}]}
I am trying to get the "contact_dt" as the title of each accordion tab and then format the rest of the elements in the body of the accordion tabs. Currently I'm getting a busy spinner when I select the Contact History tab that contains the accordion but this only yields a tiny square box in the body and does not alter the title. Here is the code that I'm sure I have mangled. First for the HTML portion...
<div id="history" title="Prospect Contact History" closable="true" style="padding:10px;">
<h2 class="atitle">Prospect Details</h2>
<div id="aa" class="easyui-accordion" style="width:500px;height:300px;">
<div title="Title1" data-options="iconCls:'icon-save'" style="overflow:auto;padding:10px;">
<h3 id="hist_title" style="color:#0099FF;">Accordion for jQuery</h3>
<p>Accordion is a part of easyui framework for jQuery.
It lets you define your accordion component on web page more easily.</p>
</div>
</div>
</div>
Now for the jQuery pieces... First is the JS to basically call the function. This is in the body at the end of the page.
<script type="text/javascript">
$('#tt').tabs({
onSelect:function(title){
if (title == 'Prospect Contact History'){
//$( "#hist_title" ).html( "Accordion function is working.");
accordionHistory();
}
}
});
</script>
Now for the function that is defined in the head and where I think the real mess is at.
function accordionHistory() {
$( "#hist_title" ).html( "Accordion function is working.");
var pp = $('#aa').accordion('getSelected'); // get the selected panel
if (pp){
pp.panel('refresh','contact_history.php?phone=' + phone); // call 'refresh' method to load new content
var temp = $('#aa').form('load',pp);
$.each( temp, function( i, val ) {
var txt1=$("<p>Time: ").html(val.contact_dt);
var txt2=$("</p><p>Method: ").html(val.method);
var txt3=$("</p><p>Who: ").html(val.who);
var txt4=$("</p><p>Note: ").html(val.note);
//$("#hist_title").html(val.contact_dt);
$("#hist_item").html(txt2,txt3,txt4);
});
}
}
I'm sure I'm displaying gross ignorance here in basic JS concepts. As I mentioned at the beginning I'm really using this as a learning exercise as well as building something useful. Any help would be greatly appreciated. Additionally, any online tutorials that might help walk me thru some of my conceptual shortcomings would be most welcome. Thanks in advance.
Well... I finally have figured out my issues. Here is the function that I'm now using to get this working.
function accordionHistory() {
var pp = $('#aa').accordion('getSelected'); // get the selected panel
if (pp){
$.ajax({
post: "GET",
url: "get_history.php?phone=" + phone,
dataType: 'json',
success: function( details ) {
$.each(details.rows, function(index, element) {
$('#hist_title').replaceWith(
'Phone: '
+ element.phone
+ 'Contact time: '
+ this.contact_dt
+ '<br/>Method: '
+ this.method
+ '<br/>Who: '
+ this.who
+ '<br/>Note: '
+ this.note
);
});
}
});
}
}
I hope some other noob like myself finds this useful.