Referencing JSON data result from API Request - Javascript - 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

Related

API call with Axios filtering response.data

I want to get the newest 8 products depend on product's date. I can get the whole products array and filter it as you see below:
const newestProducts= [];
axios.get("http://localhost:3003/products").then(response => {
let products = response.data.sort(function(a, b) {
return new Date(b.date) - new Date(a.date);
});
newstProducts = product.slice(0,7)
});
but this will be so bad if I have thousands of product, and I just need to get the newest 8 Products only
I thought about adding ?_limit=8 to the call
axios.get("http://localhost:3003/products?_limit=8").then{...}
but this also doesn't work propersly as you know because it gets me the only top 8 products of the array
Is there any way to filter the products before I get it from the server or I MUST store them all in var and then filter them
The Json File
"categories": [
{
"id": 9,
"category": "bathroom",
"date": "2020/8/3",
"name": "ullam basin mixer",
"price": 160,
"img_1": "rim_mixer_01.jpg",
"img_2": "rim_mixer_02.jpg",
"rating": 4.5,
"description": "MARMO is a complete series made of 72 models, with different shapes and sizes for different functions, that keeps uncompromised its elegant beauty. This is a Demo Online Store."
},
{
"id": 10,
"category": "bathroom",
"date": "2020/8/19",
"name": "gravida bathtub",
"price": 2100,
"img_1": "inbani_bathtub_01.jpg",
"img_2": "inbani_bathtub_02.jpg",
"rating": 4,
"description": "A young company with a wealth of experience. created in 2004, inbani has evolved into a leader in innovation thanks to a conviction to create products which truly benefit the well-being of the customer. This is a Demo Online Store. No orders shall be fulfilled."
},
{
"id": 11,
"category": "bathroom",
"date": "2020/9/9",
"name": "vulputate mixer",
"price": 300,
"img_1": "marmo_mixer_01.jpg",
"img_2": "marmo_mixer_02.jpg",
"description": "MARMO is a complete series made of 72 models, with different shapes and sizes for different functions, that keeps uncompromised its elegant beauty. This is a Demo Online Store."
},
{
"id": 12,
"category": "bathroom",
"date": "2018/7/17",
"name": "aliquam veneatis bathtub",
"price": 2580,
"img_1": "sa_oche_01.jpg",
"img_2": "sa_oche_02.jpg",
"description": "Its oval, elliptical design with the incongruent walls invokes an avant-garde atmosphere in the bathroom."
},
{
"id": 13,
"category": "kitchen",
"date": "2020/3/13",
"name": "quisque teapot",
"price": 240,
"img_1": "theo_teapot_01.jpg",
"img_2": "theo_teapot_02.jpg",
"description": "Theo Teapot is a Scandinavian-Japanese teapot made from stoneware and bamboo, designed by Unit 10 Design for Stelton. This is a Demo Online Store. No orders shall be fulfilled."
},
{
"id": 14,
"category": "kitchen",
"date": "2020/2/12",
"name": "creamic teapot",
"price": 60,
"img_1": "cer_teapot_01.jpg",
"img_2": "cer_teapot_02.jpg",
"rating": 3.9,
"description": "Matte ceramic tea pot comes with integrated and removable metal tea infuser. Capacity 700 ml (2.96 cups). Dishwasher safe. This ceramic teapot has a white matte finish, coupled with a square shape and curved lines."
},
{
"id": 15,
"category": "kitchen",
"date": "2019/2/1",
"name": "bottle grinders",
"price": 30,
"img_1": "bottle_gringer_01.jpg",
"img_2": "bottle_gringer_02.jpg",
"rating": 4.8,
"description": "Bottle Grinders is a minimal, timeless salt and pepper mill set designed by Norm.Architects for Menu. Steering away from the predictable grinder, the Norm Bottle Grinder is not what you expect to see in a salt and pepper grinder. The form, shaped more like a bottle, cleverly tricks the user to encourage a more playful and experimental interaction with the product. This is a Demo Online Store. No orders shall be fulfilled. Purchase this product"
},
{
"id": 16,
"category": "lighting",
"date": "2020/1/3",
"name": "commodo blown lamp",
"price": 275,
"img_1": "tradition_blown_01.jpg",
"img_2": "tradition_blown_02.jpg",
"description": "Blown lamp SW3 & SW4 by &tradition is a mouth-blown pendant lamp with a quilted pattern, it comes in a translucent variant with a silver lustre or in a opal white version. Blown lamp is fitted with a powder-coated metal suspension. This is a Demo Online Store. No orders shall be fulfilled."
},
{
"id": 17,
"category": "lighting",
"date": "2020/6/9",
"name": "spot table",
"price": 100,
"img_1": "spot_lamp_01.jpg",
"img_2": "spot_lamp_02.jpg",
"rating": 3.4,
"description": "Set the stage. The Spot lamp is a lively, versatile addition to your room. This is a Demo Online Store. No orders shall be fulfilled."
}
]
The problem is not in API Calling... To enhance the performance you have to refractor the DATABASE REQUEST in the backend to get the last 8 products only.
Note:
You make this through the query you send to the database in the controller (ROUTE ) in the backend

How does this functional Javascript example work?

I just don't seem to be able to wrap my head around this snippet of code. Could you give me a hint or two on it?
var filteredList = watchList.map(function(e) {
return {title: e["Title"], rating: e["imdbRating"]}
}).filter((e) => e.rating >= 8);
The question: I understand that 'e' is the parameter passed on to the callback of the map method but what are e["Title"] and e["imdbRating"]? We are expected to run this function on an array of objects. I don't understand the syntax, and how this can even invoke something. Extremely perplexed.
I UNDERSTAND WHAT THE CODE DOES BUT HOW COME ARE WE USING THIS title: e["Title"], rating: e["imdbRating"] ???
THIS IS A SAMPLE OF AN ARRAY OF OBJECTS!
var watchList = [
{
"Title": "Inception",
"Year": "2010",
"Rated": "PG-13",
"Released": "16 Jul 2010",
"Runtime": "148 min",
"Genre": "Action, Adventure, Crime",
"Director": "Christopher Nolan",
"Writer": "Christopher Nolan",
"Actors": "Leonardo DiCaprio, Joseph Gordon-Levitt, Ellen Page, Tom Hardy",
"Plot": "A thief, who steals corporate secrets through use of dream-sharing technology, is given the inverse task of planting an idea into the mind of a CEO.",
"Language": "English, Japanese, French",
"Country": "USA, UK",
"Awards": "Won 4 Oscars. Another 143 wins & 198 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjAxMzY3NjcxNF5BMl5BanBnXkFtZTcwNTI5OTM0Mw##._V1_SX300.jpg",
"Metascore": "74",
"imdbRating": "8.8",
"imdbVotes": "1,446,708",
"imdbID": "tt1375666",
"Type": "movie",
"Response": "True"
},
{
"Title": "Interstellar",
"Year": "2014",
"Rated": "PG-13",
"Released": "07 Nov 2014",
"Runtime": "169 min",
"Genre": "Adventure, Drama, Sci-Fi",
"Director": "Christopher Nolan",
"Writer": "Jonathan Nolan, Christopher Nolan",
"Actors": "Ellen Burstyn, Matthew McConaughey, Mackenzie Foy, John Lithgow",
"Plot": "A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival.",
"Language": "English",
"Country": "USA, UK",
"Awards": "Won 1 Oscar. Another 39 wins & 132 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjIxNTU4MzY4MF5BMl5BanBnXkFtZTgwMzM4ODI3MjE#._V1_SX300.jpg",
"Metascore": "74",
"imdbRating": "8.6",
"imdbVotes": "910,366",
"imdbID": "tt0816692",
"Type": "movie",
"Response": "True"
},
Here e points to the current element being processed in the array. So e will basically represent each object inside the array. You can replace e with any other valid name.
In your code first map is creating a new array of object and each object have tw keys title & imbRating , then again applying filter on it to create another new array where the value of imbRating is more than 8
var watchList = [{
"Title": "Inception",
"Year": "2010",
"Rated": "PG-13",
"Released": "16 Jul 2010",
"Runtime": "148 min",
"Genre": "Action, Adventure, Crime",
"Director": "Christopher Nolan",
"Writer": "Christopher Nolan",
"Actors": "Leonardo DiCaprio, Joseph Gordon-Levitt, Ellen Page, Tom Hardy",
"Plot": "A thief, who steals corporate secrets through use of dream-sharing technology, is given the inverse task of planting an idea into the mind of a CEO.",
"Language": "English, Japanese, French",
"Country": "USA, UK",
"Awards": "Won 4 Oscars. Another 143 wins & 198 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjAxMzY3NjcxNF5BMl5BanBnXkFtZTcwNTI5OTM0Mw##._V1_SX300.jpg",
"Metascore": "74",
"imdbRating": "8.8",
"imdbVotes": "1,446,708",
"imdbID": "tt1375666",
"Type": "movie",
"Response": "True"
},
{
"Title": "Interstellar",
"Year": "2014",
"Rated": "PG-13",
"Released": "07 Nov 2014",
"Runtime": "169 min",
"Genre": "Adventure, Drama, Sci-Fi",
"Director": "Christopher Nolan",
"Writer": "Jonathan Nolan, Christopher Nolan",
"Actors": "Ellen Burstyn, Matthew McConaughey, Mackenzie Foy, John Lithgow",
"Plot": "A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival.",
"Language": "English",
"Country": "USA, UK",
"Awards": "Won 1 Oscar. Another 39 wins & 132 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjIxNTU4MzY4MF5BMl5BanBnXkFtZTgwMzM4ODI3MjE#._V1_SX300.jpg",
"Metascore": "74",
"imdbRating": "8.6",
"imdbVotes": "910,366",
"imdbID": "tt0816692",
"Type": "movie",
"Response": "True"
}
]
var filteredList = watchList.map(function(e) {
return {
title: e["Title"],
rating: e["imdbRating"]
}
}).filter((e) => e.rating >= 8);
console.log(filteredList)
e is an object with some properties. Imagine it looks like this:
var e = {
Title: 'foo',
imdbRating: 7.2,
};
so e["Title"] will return 'foo' and e["imdbRating"] will return 7.2.
the function you posted could also be written like this:
var filteredList = watchList.map(function(e) {
return {title: e.Title, rating: e.imdbRating}
}).filter((e) => e.rating >= 8);
Maybe that makes it easier to understand.
var filteredList = watchList.map(function(e) {
return {title: e["Title"], rating: e["imdbRating"]}
}).filter((e) => e.rating >= 8);
In the above code, the map function is used to iterate all the elements from watchList array. Map iterates all the values one by one which are objects. e is assigned the object. It returns an object with property and its value as e["Title"]. It is a way of accessing the properties of an object.e["Title"] and e.imdbRating will respectively call the values related to the title and imdbRating values.
Let's split it up so it makes more sense
First, we create a new array with map. Map works by iterating over array(watchList in this case), at each iteration it passes the current array element to the provided callback function, the returned value defines that value at index i in new array where index i is the position of the element passed to the callback function.
Take for example:
const timeTwo = [1, 2, 3].map(num => num * 2);
// timesTwo = [2, 4, 6]
In the example your providing, map returns a new array of objects containing properties title, and rating. title remains the same from original array, but rating is the mapped value of e.imdbRating.
var filteredList = watchList.map(function(e){
return {
title: e.title,
rating: e.imdbRating,
};
});
Now lets look at the next part. Filter, creates a new array, by iterating over an old array, if the callback passed to filter returns true that element is added to the new array if it returns false the element is excluded.
In this case, the final value of filtered list will be an array of objects with properties title and rating, where the rating is greater than or equal to 8;
var filteredList = filteredList.filter((e) => e.rating >= 8);
Lets put it all together, watchList.map returns a new array, and all arrays have a filter method, so we can chain filter off map(like below). Finally filter, returns an array which will be stored in the variable filteredList.
var filteredList = watchList.map(function(e) {
return {title: e.Title, rating: e.imdbRating}
}).filter((e) => e.rating >= 8);

Append '|' after every array element

I have this JSON & what I want to do is to make genres like this action|adventure|comedy
{
"id": 1,
"key": "deadpool",
"name": "Deadpool",
"description": "A former Special Forces operative turned mercenary is subjected to a rogue experiment that leaves him with accelerated healing powers, adopting the alter ego Deadpool.",
"genres": [
"action",
"adventure",
"comedy"
],
"rate": 8.6,
"length": "1hr 48mins",
"img": "assets/images/movie-covers/deadpool.jpg"
},
{
"id": 2,
"key": "we-are-the-millers",
"name": "We're the Millers",
"description": "A veteran pot dealer creates a fake family as part of his plan to move a huge shipment of weed into the U.S. from Mexico.",
"genres": [
"adventure",
"comedy",
"crime"
],
"rate": 7,
"length": "1hr 50mins",
"img": "assets/images/movie-covers/we-are-the-millers.jpg"
}
my component code snippet
data => {
this.movies = data;
var tempArr= data
var genres;
let genresWithPipe=[];
let len= tempArr.length;
for(var i=0; i<len; i++){
genres=tempArr[i].genres+'|';
// console.log(tempArr[i].genres)
for(var j=0;j<genres.length; j++){
if(j<genres.length-1)
genres[j]= genres[j]+'|';
console.log(genres,data);
//genresWithPipe=genres;
}
}
console.log(this.movies,genres)
}
I have tried to do it with the help of for loop in my component but then when I am displaying it in the html with the help of *ngFor then because it's a local variable,it won't show up. If I store array values in a global variable then the variable only store the last array.
You can use map method in order to achieve your requirement and obtain a more cleaner solution.
The map() method creates a new array with the results of calling a
provided function on every element in the calling array.
Also, you can use join method in order to obtain the structure action|adventure|comedy with | delimiter.
let array=[{ "id": 1, "key": "deadpool", "name": "Deadpool", "description": "A former Special Forces operative turned mercenary is subjected to a rogue experiment that leaves him with accelerated healing powers, adopting the alter ego Deadpool.", "genres": [ "action", "adventure", "comedy" ], "rate": 8.6, "length": "1hr 48mins", "img": "assets/images/movie-covers/deadpool.jpg" }, { "id": 2, "key": "we-are-the-millers", "name": "We're the Millers", "description": "A veteran pot dealer creates a fake family as part of his plan to move a huge shipment of weed into the U.S. from Mexico.", "genres": [ "adventure", "comedy", "crime" ], "rate": 7, "length": "1hr 50mins", "img": "assets/images/movie-covers/we-are-the-millers.jpg" }];
array=array.map(function(item){
item.genres=item.genres.join('|');
return item;
});
console.log(array);
A good solution with Array.map() has been proposed, here is another option with Array.forEach():
const data = [{
"id": 1,
"key": "deadpool",
"name": "Deadpool",
"description": "A former Special Forces operative turned mercenary is subjected to a rogue experiment that leaves him with accelerated healing powers, adopting the alter ego Deadpool.",
"genres": [
"action",
"adventure",
"comedy"
],
"rate": 8.6,
"length": "1hr 48mins",
"img": "assets/images/movie-covers/deadpool.jpg"
},
{
"id": 2,
"key": "we-are-the-millers",
"name": "We're the Millers",
"description": "A veteran pot dealer creates a fake family as part of his plan to move a huge shipment of weed into the U.S. from Mexico.",
"genres": [
"adventure",
"comedy",
"crime"
],
"rate": 7,
"length": "1hr 50mins",
"img": "assets/images/movie-covers/we-are-the-millers.jpg"
}
]
const genres = [];
data.forEach(film => genres.push(film.genres.join("|")));
console.dir(genres);
Note that your data definitely doesn't look like what you put in the code sample, it must be wrapped with [].

Facebook Feed on web page infinte scrolling

I am trying to use this plugin to create an infinite scroll effect for Facebook feeds, now I get access to the feed I need through the graph api (fan page wall posts) and I limit it to 10, and even so Facebook supplies a next and previous links to the next or previous 10 posts in the actual json data, but I just can't seem to get this plugin working with it.
Heres an example of the json data:
{
"data": [
{
"id": "393459637370574_326418557474553",
"from": {
"category": "Consulting/business services",
"name": "Global Georgia",
"id": "393459637370574"
},
"to": {
"data": [
{
"name": "Global Georgia Tour",
"start_time": "2012-12-05",
"location": "Republic of Georgia",
"id": "297926606990415"
}
]
},
"message": "What a lovely trip it was!",
"picture": "http://photos-a.ak.fbcdn.net/hphotos-ak-snc7/205700_468134469903090_2092776360_s.jpg",
"link": "https://www.facebook.com/photo.php?fbid=468134469903090&set=oa.462645617136057&type=1&relevant_count=4",
"icon": "http://static.ak.fbcdn.net/rsrc.php/v2/yz/r/StEh3RhPvjk.gif",
"privacy": {
"value": ""
},
"type": "photo",
"object_id": "468134469903090",
"created_time": 1359555861,
"updated_time": 1359555861,
"likes": {
"data": [
{
"name": "Mareleen du Plessis",
"id": "1382224862"
}
],
"count": 1
},
"comments": {
"count": 0
}
},
{
"id": "393459637370574_333589073411971",
"from": {
"category": "Consulting/business services",
"name": "Global Georgia",
"id": "393459637370574"
},
"story": "Global Georgia shared a link.",
"story_tags": {
"0": [
{
"id": "393459637370574",
"name": "Global Georgia",
"offset": 0,
"length": 14,
"type": "page"
}
]
},
"picture": "http://external.ak.fbcdn.net/safe_image.php?d=AQCwYiOOZnd4DK5_&w=90&h=90&url=http\u00253A\u00252F\u00252Frsa.mfa.gov.ge\u00252FuniInc.php\u00253Fmode\u00253Dimg\u002526src_jpg\u00253Dfiles\u00252Frsa\u00252FPresentation_Credentials_to_President_Jacob_Zuma_of_South_Africa-29.01.2013.jpg\u002526im_new_w\u00253D200",
"link": "http://rsa.mfa.gov.ge/index.php?lang_id=ENG&sec_id=913&info_id=16905",
"name": "News - Embassy of Georgia to the Republic of South Africa",
"caption": "rsa.mfa.gov.ge",
"description": "On January 2013, in Pretoria, the firstAmbassador Extraordinary and Plenipotentiary of Georgia in the Republic of South Africa, Mr Beka Dvali presented his credentials to the President of the Republic of South Africa, H.E. Mr Jacob Zuma. ",
"icon": "http://static.ak.fbcdn.net/rsrc.php/v2/yD/r/aS8ecmYRys0.gif",
"privacy": {
"value": ""
},
"type": "link",
"status_type": "shared_story",
"created_time": 1359550985,
"updated_time": 1359550985,
"likes": {
"data": [
{
"name": "Ivan A Meyer",
"id": "100000016287990"
},
{
"name": "Amanda Aldum",
"id": "779374234"
},
{
"name": "Cazz Bouwer",
"id": "100001702505460"
},
{
"name": "Gigi Mikeladze",
"id": "100004658262461"
}
],
"count": 4
},
"comments": {
"count": 0
}
},
{
"id": "393459637370574_450229665031926",
"from": {
"category": "Consulting/business services",
"name": "Global Georgia",
"id": "393459637370574"
},
"story": "Global Georgia shared Embassy of Georgia in the Republic of South Africa's photo.",
"story_tags": {
"0": [
{
"id": "393459637370574",
"name": "Global Georgia",
"offset": 0,
"length": 14,
"type": "page"
}
],
"22": [
{
"id": "340928409306379",
"name": "Embassy of Georgia in the Republic of South Africa",
"offset": 22,
"length": 50,
"type": "page"
}
]
},
"picture": "http://photos-f.ak.fbcdn.net/hphotos-ak-snc7/385189_475566662509219_1872863393_s.jpg",
"link": "https://www.facebook.com/photo.php?fbid=475566662509219&set=a.405386502860569.99241.340928409306379&type=1",
"name": "Timeline Photos",
"caption": "Information on the meeting of the Ambassador of Georgia\r\nwith the National Librarian and Chief Executive Officer\r\nof the National Library of South Africa\r\n\r\nOn 24 January 2013 H.E. Mr Beka Dvali, Ambassador of Georgia held a meeting with Mr John Tsebe, the National Librarian and Chief Executive Officer of the National Library of the Republic of South Africa, and the Chair of the Conference of Directors of National Libraries (CDNL)).\r\nAmbassador of Georgia passed on Mr Tsebe several books to be catalogued as the first ever publications on Georgia at the National Library of South Africa.\r\nDuring the meeting, the parties discussed the possibilities of cooperation between the national libraries of the two countries, the issues of supplying Georgian and Georgia-related books, by the support of the Embassy, to the National Library of South Africa as well as the prospects of hosting by the library a literature event featuring contemporary Georgian author(s). \r\n\r\n24 January 2013\r\nPretoria",
"properties": [
{
"name": "By",
"text": "Embassy of Georgia in the Republic of South Africa",
"href": "https://www.facebook.com/EmbassyOfGeorgia?ref=stream"
}
],
"icon": "http://static.ak.fbcdn.net/rsrc.php/v2/yD/r/aS8ecmYRys0.gif",
"privacy": {
"value": ""
},
"type": "photo",
"status_type": "shared_story",
"object_id": "475566662509219",
"application": {
"name": "Photos",
"id": "2305272732"
},
"created_time": 1359387805,
"updated_time": 1359387805,
"comments": {
"count": 0
}
}
],
"paging": {
"previous": "https://graph.facebook.com/393459637370574/feed?limit=3&date_format=U&access_token=XXXX&since=1359555861&__previous=1",
"next": "https://graph.facebook.com/393459637370574/feed?limit=3&date_format=U&access_token=XXXX&until=1359387804"
}
}
How would I get this functionality working?
Any help/advice greatly appreciated
It looks like you'd have to spend a lot of time wrangling with infinite-scroll.js to get it to do what you want, because it depends on having pagination links in your HTML.
What would probably be easier would be to write your own Javascript to detect when the user is scrolling and automatically load stuff then, based on the next page link in your most recent JSON response.
If you look at the code for jscroll.js (a similar plugin to infinte-scroll, but with code that's a bit simpler) you'll probably a get a good idea of what to look for and when to load new content. Specifically, from line 84:
// Observe the scroll event for when to trigger the next load
function _observe() {
var $inner = $e.find('div.jscroll-inner').first(),
data = $e.data('jscroll'),
iContainerTop = parseInt($e.css('paddingTop')) + parseInt($e.css('borderTopWidth')),
iTopHeight = _isWindow ? _$scroll.scrollTop() : $e.offset().top,
innerTop = $inner.length ? $inner.offset().top : 0,
iTotalHeight = Math.ceil(iTopHeight - innerTop + _$scroll.height() + iContainerTop),
nextHref = $.trim(data.nextHref + ' ' + _options.contentSelector);
if (_checkNextHref(data) && !data.waiting && iTotalHeight + _options.padding >= $inner.outerHeight()) {
_debug('info', 'jScroll:', $inner.outerHeight() - iTotalHeight, 'from bottom. Loading next request...');
return _load();
}
}
Looking at the documentation, It seems to allow a functionality where it calls the link in the href via AJAX and returns the response to you.
If you make an initial call on pageload to populate your initial feed, then create a display: none link with something like:
#nextLink {
display: none;
}
and give it a href of the data['paging']['next'] then you could initialise the infinite scroll with something like:
$('.feedContainer').infinitescroll({
// other options
nextSelector: "a#nextLink",
dataType: 'json',
appendCallback: false
}, function(json, opts) {
// Update your next link to point to the next page
$('#nextLink').attr('href',json['data']['paging']['next']);
// Add your new feed rows here
var htmlStr = '<li>FeedContent</li>';
// Append it to the container
$('.feedContainer').append(htmlStr);
});
Use dataType 'jsonp' if it supports it.
That should roughly give you what you're looking for!

How do I get local business results using google maps API

Is there any google/Yahoo/Bing API which gives local business results based on a ZIP/GeoCode of a location? If yes, please let me know.
If Google Maps has such service, please let me know what where do I get a reference regarding that?
Disclosure: I work at SerpApi.
Is there any google/Yahoo/Bing API which gives local business results based on a ZIP/GeoCode of a location?
Yes, you can use SerpApi to get local business results based on ZIP, query, or GPS coordinates: https://serpapi.com/playground?engine=google_maps&q=coffee+Austin+TX+78747&type=search
Sample response
{
"local_results": [
{
"position": 1,
"title": "The Standard Grill",
"data_id": "0x89c259c06677ef37:0x5707f22fe7137aa2",
"gps_coordinates": {
"latitude": 40.7406697,
"longitude": -74.0079042
},
"place_id_search": "https://serpapi.com/search.json?data=%214m5%213m4%211s0x89c259c06677ef37%3A0x5707f22fe7137aa2%218m2%213d40.7406697%214d-74.0079042&engine=google_maps&google_domain=google.com&token=f01cbc346c0db944&type=place",
"rating": 4.1,
"reviews": 840,
"price": "$$$",
"type": "Bar & grill",
"address": "848 Washington St, New York, NY 10014",
"hours": "Open until 11:30 PM",
"phone": "(212) 645-4100",
"website": "http://www.thestandardgrill.com/",
"description": "Trendy, upscale American dining. Trendy, clubby, hotel-set American bistro under the High Line with sidewalk tables & lively bar.",
"editorial_reviews": {
"summary": "Where To Eat On Christmas Day In New York City",
"link": "https://www.forbes.com/sites/melissakravitz/2019/12/13/christmas-dinner-new-york-city/"
},
"thumbnail": "https://lh5.googleusercontent.com/p/AF1QipMGM_4u4iQcrdRZApFFIinDga-cb0rXu79aFxvv=w125-h92-k-no"
},
{
"position": 2,
"title": "Rockmeisha - Sake & Grill",
"data_id": "0x89c259938c3a05cb:0xa1b2fe3b945a853d",
"gps_coordinates": {
"latitude": 40.732638,
"longitude": -74.00237299999999
},
"place_id_search": "https://serpapi.com/search.json?data=%214m5%213m4%211s0x89c259938c3a05cb%3A0xa1b2fe3b945a853d%218m2%213d40.732638%214d-74.00237299999999&engine=google_maps&google_domain=google.com&token=8bcfdeb90a3d1f1a&type=place",
"rating": 4.3,
"reviews": 102,
"price": "$$",
"type": "Tapas restaurant",
"address": "11 Barrow St, New York, NY 10014",
"hours": "Opens at 6:00 PM",
"phone": "(212) 675-7775",
"website": "http://rockmeisha-izakaya.business.site/",
"description": "Japanese drink-&-snack joint. Traditional Japanese drinking establishment pairing its sake & beer with ramen & small plates.",
"editorial_reviews": {
"summary": "25 Exemplary Fried Chicken Dishes Around NYC",
"link": "https://ny.eater.com/maps/nyc-fried-chicken-best"
},
"thumbnail": "https://lh5.googleusercontent.com/p/AF1QipNA8eJZ-VZxHIV43490yYZCnjDbBbYUA9wiH_Lq=w122-h92-k-no"
}
]
}
You can use Node.js wrapper
const { GoogleSearchResults } = require('google-search-results-nodejs')
const client = new GoogleSearchResults("API_KEY")
const parameters = {
engine: "google_maps",
type: "search",
google_domain: "google.com",
q: "NY 10014 grill",
};
function onResponse(data) {
console.log(data.local_results[0])
}
client.json(parameters, onResponse)
If Google Maps has such service, please let me know what where do I get a reference regarding that?
https://serpapi.com/maps-local-results
Google does have that, you can even check few sample implementations:
http://code.google.com/apis/ajaxsearch/local.html

Categories