printing html from an api using a javascript function - javascript

I am currently creating a simple website using HTML and JavaScript, but encountering a weird error. Essentially, the website has multiple html pages that display different genres of movies as recommendations. It displays the name, the billboard poster, and a quote retrieved from an open-sourced API found online.
All javascript functions for each of the movies are the same, so for example, the one for Toy Story is:
var getToyStory = function(){
var request = new XMLHttpRequest();
request.open("GET", "http://www.omdbapi.com/?apikey=8af1471b&t=Toy+Story", true);
request.onload = function(){
var data = JSON.parse(this.response);
var Plot = data.Plot;
document.getElementById("Plot").textContent=Plot;
};
request.send();
}
I know the javascript function is working because the error I encouted is in displaying it. I call the function using the follow tags:
<body onload="getToyStory()" id = 'Plot'></body>
When called, the HTML displays ONLY the one API quote and nothing else, and does it without any of the styling from the external CSS styling sheet. It doesn't report any errors in the console section of the Chrome Developer Tools, so I am unsure how to fix it.

When using the "onload" element it means that it calls that function one time once the DOM is loaded. The request sends back a string read in and parsed by you to JSON. The response looks like this:
JSON Response
{
"Title": "Toy Story",
"Year": "1995",
"Rated": "G",
"Released": "22 Nov 1995",
"Runtime": "81 min",
"Genre": "Animation, Adventure, Comedy",
"Director": "John Lasseter",
"Writer": "John Lasseter, Pete Docter, Andrew Stanton",
"Actors": "Tom Hanks, Tim Allen, Don Rickles",
"Plot": "A cowboy doll is profoundly threatened and jealous when a new spaceman figure supplants him as top toy in a boy's room.",
"Language": "English",
"Country": "United States",
"Awards": "Nominated for 3 Oscars. 27 wins & 23 nominations total",
"Poster": "https://m.media-amazon.com/images/M/MV5BMDU2ZWJlMjktMTRhMy00ZTA5LWEzNDgtYmNmZTEwZTViZWJkXkEyXkFqcGdeQXVyNDQ2OTk4MzI#._V1_SX300.jpg",
"Ratings": [
{
"Source": "Internet Movie Database",
"Value": "8.3/10"
},
{
"Source": "Rotten Tomatoes",
"Value": "100%"
},
{
"Source": "Metacritic",
"Value": "95/100"
}
],
"Metascore": "95",
"imdbRating": "8.3",
"imdbVotes": "960,910",
"imdbID": "tt0114709",
"Type": "movie",
"DVD": "23 Mar 2010",
"BoxOffice": "$223,225,679",
"Production": "N/A",
"Website": "N/A",
"Response": "True"
}
You then create a variable to hold the "Plot" element from the JSON response making that a string that holds the following:
"A cowboy doll is profoundly threatened and jealous when a new spaceman figure supplants him as top toy in a boy's room."
Whenever you use the following javascript function, "document.getElementById("Plot").textContent=Plot;", all this is doing is telling the element with id "Plot" (your HTML body) to load the text from the "Plot" variable as inner text inside the element. Essentially it looks like this in HTML:
<body id="Plot">
A cowboy doll is profoundly threatened and jealous when a new spaceman figure supplants him as top toy in a boy's room.
</body>
If you want to add other HTML elements or CSS decorations to the page you would need to do that ahead of time then add the api response to the appropriate element (ie. <div id="Plot" class="awesome-css-stuff"></div>).

Related

What is the proper format for HTTP POST Dynamic Zone data with Strapi API?

I have a Strapi user collection that looks like this.
I am trying to use the API to create a new user with the "AdditionalInfo" dynamic zone filled with "StudentUserInfos" component.
What would my HTTP POST request Body look like?
I can not find documentation or example on how to do it anywhere. I have tried:
{
"username" : "string",
"password" : "string",
"email" : "string",
"AdditionalInfo": [
{
"__component": "user-type.student-user",
"Address": "string",
"ParentsName": "string",
"ParentsPhoneNumber": "string",
"SchoolName": "string",
"OtherInfo": "string"
}]
It gives me a Bad Request response. What is the proper format for this? Can you please point me to an example?
After digging a little bit, you should send your JSON like this:
{
"...otherFields"
"industry": "61f83aa80f6439632bac3579",
"additional_info": [
{
"__component": "fields.seller-fields",
"country": {
"isoCode": "US",
"name": "United States"
},
"state": {
"isoCode": "CA",
"name": "California"
},
"year_established": 2022,
"size": "10000+"
}
]
}
Where "additional_info" is the name of the dynamic zone and "fields.seller-fields" the name of the component. I would recommend creating a dummy dynamic zone through Strapi GUI and then fetching it and seeing how dynamic zones are stored. (That's how I figured out the name of the component). Check the image below
strapi dynamic zones example

How to add images in flags in timeline.js

I am using timeline.js. i am new to timeline.js. I want to add the image in flag which is shown on timeline with different image icons for different points. I didn't get any solution for this in documentation or anything. Image of where i want to add image is shown in the image attached. flag_image
Please find the demo in following link. Codepen
var dataObject = {
"timeline": {
"headline": "Welcome to TimelineJS",
"startDate": "2011,12,10",
"type": "default",
"text": "<p>TimelineJS is an open-source tool that enables you to build visually-rich interactive timelines and is available in 40 languages.</p><p>You're looking at an example of one right now.</p><p>Click on the arrow to the right to learn more.</p>",
"asset": {
"media": "https://2.bp.blogspot.com/-dxJbW0CG8Zs/TmkoMA5-cPI/AAAAAAAAAqw/fQpsz9GpFdo/s1600/voyage-dans-la-lune-1902-02-g.jpg",
"credit": "",
"caption": ""
},
"date": [{
"startDate": "2011,12,10",
"headline": "Exception initiated by XYZ",
"asset": {
"media": "/static/welcome/step3.png",
"credit": "",
"caption": "Screenshot from TimelineJS Embed Generator tool (see below)"
}
}, {
"startDate": "2012,12,10",
"headline": "Exception initiated by XYZ",
"asset": {
"media": "/static/welcome/step3.png",
"credit": "",
"caption": "Screenshot from TimelineJS Embed Generator tool (see below)"
}
}, {
"startDate": "2011,12,11",
"headline": "Tech review approved by ABC",
"text": "Timeline can automatically pull in photos, videos from YouTube or Vimeo, tweets, wikipedia entries, and many other media types to help tell your story.",
"asset": {
"media": "",
"credit": "",
"caption": "Screenshot from TimelineJS Embed Generator tool (see below)"
}
}, {
"startDate": "2011,12,12",
"headline": "Approved by all",
"text": "Timeline can automatically pull in photos, videos from YouTube or Vimeo, tweets, wikipedia entries, and many other media types to help tell your story.",
"asset": {
"media": "",
"credit": "",
"caption": "Screenshot from TimelineJS Embed Generator tool (see below)"
}
}, {
"startDate": "2011,12,13",
"headline": "Closure requested",
"text": "Timeline can automatically pull in photos, videos from YouTube or Vimeo, tweets, wikipedia entries, and many other media types to help tell your story.",
"asset": {
"media": "https://image.ibb.co/eMGfya/episodic_failed.png",
"credit": "",
"caption": "Screenshot from TimelineJS Embed Generator tool (see below)"
}
}],
"era": [{
"startDate": "2011,12,10",
"endDate": "2011,12,11",
"headline": "Revision1",
"tag": "This is Optional"
}, {
"startDate": "2011,12,13",
"endDate": "2011,12,14",
"headline": "Revision2",
"tag": "This is Optional"
}
]
}
}
createStoryJS({
type: 'timeline',
width: '800',
height: '600',
source: dataObject,
embed_id: 'my-timeline',
hash_bookmark: true
});
.classRed
{
background-color:red;
}
/* .vco-slider .slider-container-mask {
display: none;
} */
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://cdn.knightlab.com/libs/timeline/latest/js/storyjs-embed.js"></script>
<link href="https://cdn.knightlab.com/libs/timeline/latest/css/timeline.css" rel="stylesheet"/>
<div id="my-timeline"></div>
You would need to add the image into the div element that represents the flag.
An easy way to do this is to use the browser Dev tools on an open timeline, use the element click tool to select a flag, determine the class used by flags (as well as a set of classes that makes a unique path is CSS class names to a flag) and use jquery/javascript to position an image element inside the the identified div element (that is, the flag).
In terms of using an image for each flag based on the type of event (of the flag), you will likely need to use text from your event to identify it in a div (like in the .each method of jquery after you apply the selector).
I am suggesting this as I changed the color of the flag based on types of event I had defined, and used the event type in the title field, parsed that text for the event name (the type was added as first word, so I parsed the string from position 0) and then changed the background-color CSS attribute (with !important).
BTW, I took this approach so as to not change the source code (post-processing the DOM).
Hope this helps some

Referencing JSON data result from API Request - Javascript

I'll start out by saying that I am a pretty new web developer, so I apologize if this is overly basic... I just couldn't find it anywhere on Google. I'm receiving JSON data back from an API call to omdb, and I am unsure how to reference a line in the data Specifically, I am trying to reference the Rotten Tomatoes Value, and this needs to be repeatable for any movie I search. I started by storing the response in JSON and then working through each item I need:
var body = JSON.parse(body);
console.log("Title: " + body.Title);
console.log("Release Year: " + body.Year);
console.log("IMdB Rating: " + body.imdbRating);
console.log("Country: " + body.Country);
console.log("Language: " + body.Language);
console.log("Plot: " + body.Plot);
console.log("Actors: " + body.Actors);
console.log("Rotten Tomatoes Rating: " + body.Ratings.????RottenTomatoes???);
It's just the Rotten Tomatoes Value Line I can't figure out! Everything else works. To clarify, this is just a JSON referencing issue I cannot figure out.
{
"Title": "Anastasia",
"Year": "1997",
"Rated": "G",
"Released": "21 Nov 1997",
"Runtime": "94 min",
"Genre": "Animation, Adventure, Drama",
"Director": "Don Bluth, Gary Goldman",
"Writer": "Susan Gauthier (screenplay), Bruce Graham (screenplay), Bob Tzudiker (screenplay), Noni White (screenplay), Eric Tuchman (animation adaptation)",
"Actors": "Meg Ryan, John Cusack, Kelsey Grammer, Christopher Lloyd",
"Plot": "The last surviving child of the Russian Royal Family joins two con men to reunite with her grandmother, the Dowager Empress, while the undead Rasputin seeks her death.",
"Language": "English, Russian, French",
"Country": "USA",
"Awards": "Nominated for 2 Oscars. Another 10 wins & 21 nominations.",
"Poster": "https:\/\/images-na.ssl-images-amazon.com\/images\/M\/MV5BNGJiNWFlYTMtZTBiZi00ZTVmLWJmZmMtNzEzYzZjNzYzZmRmXkEyXkFqcGdeQXVyNTA4NzY1MzY#._V1_SX300.jpg",
"Ratings": [
{
"Source": "Internet Movie Database",
"Value": "7.1\/10"
},
{
"Source": "Rotten Tomatoes",
"Value": "85%"
},
{
"Source": "Metacritic",
"Value": "59\/100"
}
],
"Metascore": "59",
"imdbRating": "7.1",
"imdbVotes": "94,074",
"imdbID": "tt0118617",
"Type": "movie",
"DVD": "16 Nov 1999",
"BoxOffice": "N\/A",
"Production": "20th Century Fox",
"Website": "N\/A",
"Response": "True"
}
The Rotten tomatoes value is in the 3rd element of the array. Array indexes start at 0. Therefore, what you need is body.Ratings[2].Value.
If the order of the Ratings array is unpredictable, use filter function as below.
//If the order of the source array is unpredictable
//use filter
var rtValue = body.Ratings.filter(function(source) {
return source.Source === "Rotten Tomatoes";
}).Value;
That's because it is an array inside an object. body.Ratings[0]. You are referencing the spot of an array. Definitely look into arrays.
"Ratings": [ { "Source": "Internet Movie Database", "Value": "7.1/10" }, { "Source": "Rotten Tomatoes", "Value": "85%" }, { "Source": "Metacritic", "Value": "59/100" } ]
See the [ square brackets ] Each object inside {} can be referenced with an integer inside [0], [1] etc.
Look at some online tutorials. www.w3schools.com/js is a great place to start

Is there any way to get the photo of the books that a user likes on facebook after loging in on website?

So I managed to implement the user login facebook button on my website, and successfully get the books that the user likes on his personal facebook page, but this returns only the ID of the book and the name.
I was wondering if there is any way I could get more info about the object, like : what type of book is it ( SF, Action, For kids etc... ) or at least a photo for it, if there is any on facebook for it.
Any ideas on how I can manage to do this?
As a side note ( dunno if it will give any ideas for you guys ), I'm making an e-commerce website that after you login with your facebook account on the website I want to recommend those books that you liked/read on facebook, but I can only do that if I know them, and if the website doesn't have them I would like to make a new db entry with them, that's why I want to get more details about the item ( photo, gender etc.. )
The same I would like to apply even for movies and Songs.
Any ideas will be appreciated.
if you make a query with me/books, or v2.0/user_id/books, here's a sample result:
{
"category": "Book",
"name": "Atharva Veda",
"created_time": "2012-01-22T16:27:00+0000",
"id": "111018182244878"
},
{
"category": "Book",
"name": "Petronius' Satyricon",
"created_time": "2012-01-22T16:24:45+0000",
"id": "107943872570178"
},
{
"category": "Book",
"name": "De Brevitate Vitae",
"created_time": "2012-01-22T16:24:44+0000",
"id": "108092199212156"
},
{
"category": "Book",
"name": "Myth of Faraway Winds, an Ebook by Sarah S. Vati",
"created_time": "2012-08-20T23:26:20+0000",
"id": "390942770973133"
},
The category is, unfortunately, just "book" (I also see community pages or interests in the list of my books), but you have the book title. You can get a description with the book id, i.e., v2.0/book_id. If we want info about the book with id 390942770973133, we call the url v2.0/390942770973133, and here's the result:
{
"id": "390942770973133",
"about": "Myth of Faraway Winds is a special issue of Sarasvati Gallery's Art Catalogues, featuring the event \"Sarasvati Gallery in Atessa (Abruzzo, Italy)\".",
"can_post": true,
"category": "Book",
"checkins": 0,
"description": "Myth of Faraway Winds is a special issue of Sarasvati Gallery's Art Catalogues, featuring the event \"Sarasvati Gallery in Atessa (Abruzzo, Italy)\".",
"has_added_app": false,
"is_community_page": false,
"is_published": true,
"likes": 2,
"link": "http://www.smashwords.com/books/view/217352",
"name": "Myth of Faraway Winds, an Ebook by Sarah S. Vati",
"parking": {
"lot": 0,
"street": 0,
"valet": 0
},
"talking_about_count": 0,
"were_here_count": 0
}e_count": 0
}
You get the book cover at the following url: https://graph.facebook.com/BOOK_ID/picture, so, for the book above, it would be https://graph.facebook.com/390942770973133/picture (that's not a query, it's the url that redirects to the book picture. Put it in your browser to see it).

Google News Api custom search

I have this java script in my html file....I have a keyword search in my webpage, and I want to pass the keyword search to the API. This is what I currently have: Not sure where I am going wrong that it is not producing any search results.
where I have
CNN
in the code, this is where my search variable should be passed...
<script type="text/javascript">
google.load('search', '1');
function OnLoad()
{
var customSearchControl = new google.search.CustomSearchControl('CNN');
customSearchControl.setResultSetSize(google.search.Search.FILTERED_
CSE_RESULTSET);
customSearchControl.draw('cse');
customSearchControl.execute("$q");
}
google.setOnLoadCallback(OnLoad);
// tell the searcher to draw itself and tell it where to attach
// create a drawOptions object
var drawOptions = new google.search.DrawOptions();
// tell the searcher to draw itself in tabbed mode
drawOptions.setDrawMode(google.search.SearchControl.DRAW_MODE_TABBED);
searchControl.draw(document.getElementById("content"),drawOptions);
searchControl.addSearcher(new google.search.NewsSearch());
}
google.setOnLoadCallback(OnLoad);
</script>
You can use a third party solution like this one: https://serpapi.com/news-results
It works in a very similar way as the Google regular search, just pass the tbm=nws to your url.
https://serpapi.com/search.json?q=Trump&tbm=nws&location=Dallas&hl=en&gl=us
Results:
{
...
"news_results": [
{
"position": 1,
"title": "Trump blasts Sessions over indictments of two of his earliest ...",
"link": "https://www.cnn.com/2018/09/03/politics/donald-trump-jeff-sessions-justice-department/index.html",
"source": "CNN",
"date": "4 hours ago",
"snippet": "(CNN) President Donald Trump on Monday blasted his Attorney General Jeff Sessions and lamented the indictments of two lawmakers who ...",
"thumbnail": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSCv3eR2GkOR3WgDNTd4LqT77Bteu_ScA8NUFKcEYU1HskYXHXrnse-GnG0SN78_uUgM1k0nIQV"
},
{
"position": 2,
"title": "Trump accuses Sessions of hurting Republican congressional races",
"link": "https://www.reuters.com/article/us-usa-trump-sessions/trump-accuses-sessions-of-hurting-republican-congressional-races-idUSKCN1LJ231",
"source": "Reuters",
"date": "3 hours ago"
},
{
"position": 3,
"title": "Trump steams at Attorney General Jeff Sessions, reigniting his attacks",
"link": "https://abcnews.go.com/Politics/trump-steams-attorney-general-jeff-sessions-reigniting-attacks/story?id=57579418",
"source": "ABC News",
"date": "3 hours ago"
},
{
"position": 4,
"title": "Trump slams Sessions on Twitter, says AG is hurting GOP in midterms",
"link": "http://www.foxnews.com/politics/2018/09/03/trump-slams-sessions-on-twitter-says-ag-is-hurting-gop-in-midterms.html",
"source": "Fox News",
"date": "4 hours ago"
},
{
"position": 5,
"title": "Trump blasts Sessions over charges against GOP congressmen ...",
"link": "https://www.politico.com/story/2018/09/03/donald-trump-jeff-sessions-tweet-806298",
"source": "Politico",
"date": "5 hours ago"
},
...
],
...
}
I have the same issue and I think that the problem is these specialized CSEs have been 'deprecated' since 2010 ( see http://code.google.com/apis/websearch/) and now they just don't work. The new ones that do work are for general web search and image search. You can probably restrict the web search one to the CNN site if that's your goal. See What are the alternatives now that the Google web search API has been deprecated?

Categories