Query from different classes - javascript

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

Related

Multiple lookups to get a wordpress blog json's feed

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.

ServiceNow UI Page GlideAjax

I created a form using UI Page and am trying to have some fields autopopulated onChange. I have a client script that works for the most part, but the issue arises when certain fields need to be dot-walked in order to be autopopulated. I've read that dot-walking will not work in client scripts for scoped applications and that a GlideAjax code will need to be used instead. I'm not familiar with GlideAjax and Script Includes, can someone help me with transitioning my code?
My current client script looks like this:
function beneficiary_1(){
var usr = g_user.userID;
var related = $('family_member_1').value;
var rec = new GlideRecord('hr_beneficiary');
rec.addQuery('employee',usr);
rec.addQuery('sys_id',related);
rec.query(dataReturned);
}
function dataReturned(rec){
//autopopulate the beneficiary fields pending on the user selection
if(rec.next()) {
$('fm1_ssn').value = rec.ssn;
$('fm1_address').value = rec.beneficiary_contact.address;
$('fm1_email').value = rec.beneficiary_contact.email;
$('fm1_phone').value = rec.beneficiary_contact.mobile_phone;
var dob = rec.date_of_birth;
var arr = dob.split("-");
var date = arr[1] + "/"+ arr[2] + "/" + arr[0] ;
$('fm1_date_of_birth').value = date;
}
}
fm1_address, fm1_email, and fm1_phone do not auto populate because the value is dot walking from the HR_Beneficiary table to the HR_Emergency_Contact table.
How can I transform the above code to GlideAjax format?
I haven't tested this code so you may need to debug it, but hopefully gets you on the right track. However there are a couple of steps for this.
Create a script include that pull the data and send a response to an ajax call.
Call this script include from a client script using GlideAjax.
Handle the AJAX response and populate the form.
This is part of the client script in #2
A couple of good websites to look at for this
GlideAjax documentation for reference
Returning multiple values with GlideAjax
1. Script Include - Here you will create your method to pull the data and respond to an ajax call.
This script include object has the following details
Name: BeneficiaryContact
Parateters:
sysparm_my_userid - user ID of the employee
sysparm_my_relativeid - relative sys_id
Make certain to check "Client callable" in the script include options.
var BeneficiaryContact = Class.create();
BeneficiaryContact.prototype = Object.extendsObject(AbstractAjaxProcessor, {
getContact : function() {
// parameters
var userID = this.getParameter('sysparm_my_userid');
var relativeID = this.getParameter('sysparm_my_relativeid');
// query
var rec = new GlideRecord('hr_beneficiary');
rec.addQuery('employee', userID);
rec.addQuery('sys_id', relativeID);
rec.query();
// build object
var obj = {};
obj.has_value = rec.hasNext(); // set if a record was found
// populate object
if(rec.next()) {
obj.ssn = rec.ssn;
obj.date_of_birth = rec.date_of_birth.toString();
obj.address = rec.beneficiary_contact.address.toString();
obj.email = rec.beneficiary_contact.email.toString();
obj.mobile_phone = rec.beneficiary_contact.mobile_phone.toString();
}
// encode to json
var json = new JSON();
var data = json.encode(obj);
return data;
},
type : "BeneficiaryContact"
});
2. Client Script - Here you will call BeneficiaryContact from #1 with a client script
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
if (isLoading || newValue === '') {
return;
}
var usr = g_user.userID;
var related = $('family_member_1').value;
var ga = new GlideAjax('BeneficiaryContact'); // call the object
ga.addParam('sysparm_name', 'getContact'); // call the function
ga.addParam('sysparm_my_userid', usr); // pass in userID
ga.addParam('sysparm_my_relativeid', related); // pass in relative sys_id
ga.getXML(populateBeneficiary);
}
3. Handle AJAX response - Deal with the response from #2
This is part of your client script
Here I put in the answer.has_value check as an example, but you may want to remove that until this works and you're done debugging.
function populateBeneficiary(response) {
var answer = response.responseXML.documentElement.getAttribute("answer");
answer = answer.evalJSON(); // convert json in to an object
// check if a value was found
if (answer.has_value) {
var dob = answer.date_of_birth;
var arr = dob.split("-");
var date = arr[1] + "/"+ arr[2] + "/" + arr[0];
$('fm1_ssn').value = answer.ssn;
$('fm1_address').value = answer.address;
$('fm1_email').value = answer.email;
$('fm1_phone').value = answer.mobile_phone;
$('fm1_date_of_birth').value = date;
}
else {
g_form.addErrorMessage('A beneficiary was not found.');
}
}

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))
})

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);
};
})

Passing Variable from JSON data

I am building a mobile app using Titanium for ios and I am having a tough time getting my arms wrapped around passing variables. I am using a combination of local database and remote database to deliver my data. In this case I want to pass the data on the tableViewRow selected. The label that displays the data I call "categorydescription". In my table.addEventListener, I want to pass that data as the title for the new window and I will pass that same data to my php file on the remote server. Here is the code I am trying to use:
var xhr = Ti.Network.createHTTPClient({
onload: function() {
Ti.API.debug(this.responseText);
var json = JSON.parse(this.responseText);
for (i = 0; i < json.cms_client.length; i++) {
client = json.cms_client[i];
row = Ti.UI.createTableViewRow({
height:'44dp',
hasChild:true
});
var categorydescription = Ti.UI.createLabel({
text:client.catdesc,
font:{fontSize:'16dp', fontWeight:'bold'},
height:'auto',
left:'10dp',
color:'#000'
});
row.add(categorydescription);
tableData.push(row);
}
table.addEventListener('click',function(e) {
var win = Ti.UI.createWindow({url: 'clients.js', title: ??});
var catdesc = ??;
win.catdesc = catdesc;
Titanium.UI.currentTab.open(win,{animated:true});
});
table.setData(tableData);
Would someone be so kind to tell me what I need to put in place of the ?? in the 'title' and 'var catdesc' above?
Just add the category description and title to the row object itself:
row = Ti.UI.createTableViewRow({
height:'44dp',
hasChild:true,
categoryDescription : client.catdesc, //Add this
clientTitle : client.title // Add this
});
Now get them in the listener:
table.addEventListener('click',function(e) {
var win = Ti.UI.createWindow({url: 'clients.js', title: e.row.title});
var catdesc = e.row.categoryDescription;
win.catdesc = catdesc;
Titanium.UI.currentTab.open(win,{animated:true});
});

Categories

Resources