Multiple lookups to get a wordpress blog json's feed - javascript

I am trying to get the json for a wordpress blog - but it appears it requires multiple lookups on each news element to get the image.
The json array comes back from the server, but then provides a url to do a lookup for each image. I started to write a function to get the blog json and merge it into one array object - but I am unsure now how to proceed.
here is a jsfiddle
http://jsfiddle.net/emodsbjz/2/
buildBlogObj(data){
let imageBlogArrayUrl = [];
let blogJson = [];
for (var i = 0; i < data.length; i++) {
console.log(data[i]);
let obj = {
"label" : data[i].title.rendered,
"body" : data[i].content.rendered,
"image" : "placeholder.jpg"
}//placeholder image
imageBlogArrayUrl.push(data[i]["_links"]["wp:featuredmedia"][0]["href"]);
blogJson.push(obj);
}
blogJson = blogJson.slice(0, 4);//latest 4
this.setState({ blogs: blogJson });
console.log("blogJson", blogJson);
console.log("imageBlogArrayUrl", imageBlogArrayUrl);
let imageBlogArray = [];
for (var i = 0; i < imageBlogArrayUrl.length; i++) {
this.props.fetchBlogImage(imageBlogArrayUrl[i], function(resp){
imageBlogArray.push(resp.data.source_url)
})
}
console.log("imageBlogArray", imageBlogArray);
//let that = this;
//blogJson[i]["image"] = resp.data.source_url;
//that.setState({ blogs: blogJson });
//that.setState({ blogJson[i]["image"]: resp.data.source_url });
}
componentDidMount(){
let that = this;
this.props.fetchBlog(function(resp){
that.buildBlogObj(resp.data);
});
}

In case you want to get the featured image URL for each blog post, you can append the ?_embed at the end of the REST API endpoint to get the URL of each image along with the rest of the data:
https://www.bizzfizz.co.uk/wp-json/wp/v2/posts?_embed
The featured image URL can be found in the _embedded['wp:featuredmedia'][0].source_url object path.

Related

Show all objects present in localStorage on a webpage

I am storing my data from a form in localstorage in the following format:
Object {title: "dsadasds", dueDate: "dsadasdsa", summary: "dsadadas", body: "dasdasdas"}
Object {title: "dasdadsa", dueDate: "dasdasdadasda", summary: "dsadasdasd", body: "dasdasdas"}
This data is stored in localstorage every time a user submits the form. Now in a different page 'localhost:3000/notes' i wanna show all these objects stored in localStorage. Currently with the following code, its just showing the last object submitted.
var form = $('#form'),
formTitle = $('#title'),
formDueDate = $('#dueDate'),
formSummary = $('#summary'),
formBody = $('#body');
var title = formTitle.val();
var dueDate = formDueDate.val();
var summary = formSummary.val();
var body = formBody.val();
var newContent2 = $('#new-content2')
var test = {};
test = {
title: title,
dueDate: dueDate,
summary: summary,
body: body
}
localStorage.setItem('test', JSON.stringify(test));
var LocalStoredData = JSON.parse(localStorage.getItem('test'));
console.log(LocalStoredData);
//for retrieving data from locastorage
var retrievedData = localStorage.getItem('test');
var text = JSON.parse(retrievedData);
var showTitle = text["title"];
var showDueDate= text["dueDate"];
var showSummary = text["summary"];
var showBody = text["body"];
$('#showTitle').html(showTitle);
$('#showDueDate').html(showDueDate);
$('#showSummary').html(showSummary);
$('#showBody').html(showBody);
I need to loop trough all the objects (or any other mechanism) to extract all the objects from localStorage and display them in appropriate div on the web page. I tried putting the retrieval code in the loop:
for(var i=0;i<localStorage.length;i++)
but using this loop its not showing anything. How can I show all the objects present in my localStorage.
You're looking for
for (var i=0; i<localStorage.length; i++) {
var key = localStorage.key(i);
var item = localStorage.getItem(key);
try {
item = JSON.parse(item);
} catch(e) {
console.log(key+" is not in JSON format");
}
…
}
You can also easily get all the contents of LocalStorage using Object.keys:
Object.keys(localStorage).forEach(key => {
console.log(key, localStorage.getItem(key))
})

Query from different classes

i am using Parse platform as backend, and i have Posts and Media classes.
each (img, file, ....) in Parse object inside Media class, and each one have column with pointer to Post object from Posts class.
i am trying to get all posts with media for each post, how i can do it with one query?
var Posts = Parse.Object.extend("posts");
var query = new Parse.Query(Posts);
var newObject = [];
query.find().then(function(data){
for (var i = 0; i < data.length; i++) {
var item = data[i].toJSON();
var newData = {};
newData.objectId = item.objectId;
newData.user = {
userId: item.user.objectId,
fullName: item.user.fullName,
picture: item.user.imageUrl,
userName: item.user.userName,
};
newData.date = item.createdAt;
newData.hasImages = item.hasImages;
newData.postBody = item.postBody;
if(item.hasImages){
var Media = Parse.Object.extend("media");
var mediaQuery = new Parse.Query(Media);
mediaQuery.limit(10);
mediaQuery.descending("createdAt");
mediaQuery.matches("post", item.objectId);
mediaQuery.find().then(function(data){
newData.images = data;
});
}
newObject.push(newData);
}
console.log(newObject);
});
The best approach will be to have one to many relationship between the Post of the Media so each Post contains multiple Media objects and then you can use the following code in order to get all posts with all medias under it..
var Posts = Parse.Object.extend("posts");
var query = new Parse.Query(Posts);
// add some coditions to the Posts query here if needed
query.include("media"); // include the media relation (0..n)
// if you want to fetch only posts that have media under it you can use the following line of code
query.exists("media"); // make sure that only posts with media will be populated
query.find().then(function(posts){
// here you have the list of posts
// in order to access property of a post you can use the following code:
for (var i=0;i < posts.length;i++){
var post = posts[i];
var postMedia = post.get("media"); // get all media objects in a specific post
//..
}
},function(error){
// error
});
You can read more about Parse relations in here

How can I get nested json array data with varying key names and content inside?

I have a json array I am trying to get data out of. Here is what I am looking at currently:
I have below the jquery/javascript I used to generate this and give me this data that I can play with and the important part here is the nodes object below, this is what gets the different layouts:
var getPosts = function() {
$.ajax({
url: '/wp-json/posts?type=case-studies',
data: {
filter: {
'name': _last
}
},
success: function ( dataS ) {
//List some global variables here to fetch post data
// We use base as our global object to find resources we need
var base = dataS[0];
console.log(base);
var postContent = base.content;
var postTitle = base.title;
// Main Image ACF object
var featuredImage = base.meta.main_image;
// Gallery ACF object
var nodes = base.meta.work_content;
// Simple ACF object
//var textArea = base.meta.work_content[1];
var items = [];
for(var i = 0; i < nodes.length; i++)
{
var layout = nodes[i];
var layoutNames = layout.acf_fc_layout;
items.push( layout.acf_fc_layout['gallery']);
console.log(layout);
};
$('<div>', {
"class":'loaded',
html:items.join('')
}).appendTo(projectContainer);
},
cache: false
});
};
** edited here with json itself **
The json file here
The order these items comes in is very important and it cannot be manipulated and what I need to do is get each object and append into a container with each object using a different markup layout.
Each object has acf_fc_layout as its key that is different, my question is how can I differentiate the different data I get with that key and offer different markup for each one? I know that some will need further loops created to get images etc and I can do that. The other important thing to remember here is that there will be multiple of the same acf_fc_layout items but with different content inside them.
Cheers
var items = [];
var layoutNames = [];
for(var i = 0; i < nodes.length; i++)
{
var layout = nodes[i];
layoutNames.push(layout.acf_fc_layout);
console.log(layout);
};
//now loop on each layoutNames
$(layoutNames).each(function (){
for(var i = 0; i < nodes.length; i++)
{
var layout = nodes[i];
if(layout.acf_fc_layout==$(this).val())
//Perform Operation either image / video / page layout
console.log(layout);
};
})

insert the friends photos in a database in array

function getUserFriends(a) {
var id=a;
FB.api('/me/friends?fields=picture', function (response) {
//console.log('Got friends: ', id);
var x = y = 0;
var photos=[];
for (var i=0;i < response.data.length;i++) {
photos = response.data[i].picture.data.url;
$.post("insert_photo.php", {
"pic": photos,
"id":id
}, function (data) {
});
}
}
I am using a Facebook API to call my friends friends profile pic and using a post inserting into the db , suppose if i have 500 friends , it will send the post request 500 times , now i want to store it in the array and then the post request . is it possible , if yes please tell me how
I am not sure if I understood you, but if you want to do only one POST call, you could move the $.post() outside of the for loop. And then send all the photos array as json.
For example:
function getUserFriends(a) {
var id=a;
FB.api('/me/friends?fields=picture', function (response) {
//console.log('Got friends: ', id);
var x = y = 0;
// Storing all photo urls in array
var photos=[];
for (var i=0;i < response.data.length;i++) {
photos.push(response.data[i].picture.data.url);
}
// Send photos as JSON
$.post("insert_photo.php", {
"pics": photos,
"id":id
}, function (data) {}
);
}
This will send all the photos in a single POST call. You will have to update the insert_photo.php script to iterate over the "pics" param. Something like:
<?php
[...]
foreach (json_decode($_POST['pics']) as $pic) {
[...]
// You can use $pic here
[...]
}
[...]
Getting Friends
v2.0 onwards, getting the list of friends with /me/friends has been removed. So, the method you are using will be removed in a few months.
But there is another option now to get the friends (basically the taggable friends) with end point /me/taggable_friends; but this needs to be approved first. (Check out the complete discussion)
Save profile pictures
If you want to save the urls in an array and then make the post requests, you can do that too-
FB.api('/me/taggable_friends', function (response) {
var x = y = 0;
var photos=[];
for (var i=0;i < response.data.length;i++) {
var user={};
user.photo = response.data[i].picture.data.url;
user.id = response.data[i].id;
photos.push(user);
}
// at this point all the friends data have been saved in the array
for(var i=0; i<photos.length;i++){
$.post("insert_photo.php", {
"pic": photos[i].photo,
"id":photos[i].id
}, function (data) {
// done
});
}
});
Or the cleaner way-
Send the photos array to the php script and let php script loop through it and save to the db-
$.post("insert_photo.php", {
"data": JSON.stringify(photos)
}, function (data) {
// done
});

Can't get 9GAG feed

I am creating a 9GAG reader app for Windows 8 by using RSS Feeds and WinJS.
Code:
function downloadBlogFeed() {
WinJS.xhr({ url: "http://feeds.feedburner.com/9GAG" }).then(function (rss) {
var items = rss.responseXML.querySelectorAll("item");
for (var n = 0; n < items.length; n++) {
var article = {};
article.title = items[n].querySelector("title").textContent;
var thumbs = items[n].querySelectorAll("thumbnail");
if (thumbs.length > 1) {
article.thumbnail = thumbs[1].attributes.getNamedItem("url").textContent;
article.content = items[n].textContent;
articlesList.push(article);
}
}
});
}
Problem is that I can't get 9GAG Feeds from FeedBurner. I get this error:
Can't load http://feeds.feedburner.com/~d/styles/itemcontent.css. An app can’t load remote web content in the local context.
I have also tried changing
WinJS.xhr({ url: "http://feeds.feedburner.com/9GAG" })
with
WinJS.xhr({ url: "http://9gag.com/?feed=rss" })
but I get this error:
Exception is about to be caught by JavaScript library code at line 50, column 13 in ms-appx://7df7a30e-2f19-4f36-b368-c456fde8aabd/js/default.js
0x800a138f - JavaScript runtime error: Unable to get property 'querySelectorAll' of undefined or null reference
File: default.js
and it points to this line:
var items = rss.responseXML.querySelectorAll("item");
Can you please help me, make it right?
Thank you !
Here you go:
Unfortunately there is some hacking to get the image but alas it works, such is life with a 3rd party RSS feed.
WinJS.xhr({ url: "http://feeds.feedburner.com/9GAG", responseType: 'responseXML' }).then(function (rss) {
var items = rss.responseXML.querySelectorAll("item");
for (var n = 0; n < items.length; n++) {
var article = {};
article.title = items[n].querySelector("title").textContent;
var imageStart = items[n].textContent.indexOf('<img src="') + 11;
var imageEnd = items[n].textContent.indexOf('"', imageStart);
article.thumbnail = items[n].textContent.substring(imageStart, imageEnd);
article.content = items[n].textContent;
articlesList.push(article);
}
});
9GAG RSS feed is dead now, try to use a mirror like http://9gagrss.com/

Categories

Resources