Get data out from callback inside query - javascript

I am trying to get data out from query inside the query. I tried everything without success.
getvideos() {
var sectionHolder = [];
var ids = [];
var titles = [];
var videos = [];
var challengeCl = Parse.Object.extend("Challenges");
var query = new Parse.Query(challengeCl);
query.find().then((data) => {
for(var key = 0; key < data.length; key++) {
var object = data[key];
var videoid = object.id;
var title = object.get('title');
ids.push(videoid)
titles.push(title)
var video = Parse.Object.extend('Videos');
var queryv = new Parse.Query(video);
queryv.equalTo('challengeid', videoid);
queryv.find().then(
(video) => {
videos.push(video); //i want to get this data out from this scope
});
sectionHolder.push({title: title, data: videos}); // <---- i want to put videos data in data
}
console.log(sectionHolder);
this.setState({listData: sectionHolder});
});
}
I read parse documentation but there is nothing related to this.

Related

Updating the query data in cloud firestore nested map fields

I'm trying to update the data in nested map fields in firestore, my form is a window form that has 4 sides (wSide1,wSide2,wSide3,wSide4), what my form is doing is if customer select 1 field which is wSide1 and it needs to be updated then only this field only be updated but in my case it is updating all 4 sides, the one which is selected for example side 1 only that has the correct updated values other 3 sides updates with the false values. as my form is dynamic it only shows the field which is selected.
I only want to update the field which is selected, all other has to be null.
js & firestore query
function updateWindowForm(form, type){
var name = $('#name_'+type).val();
var type = $('#type_'+type).val();
const taskformWindow = document.getElementById("taskformWindow");
let editStatus = false;
let id = '';
const updateTask = (id, updatedTask) => db.collection('Buildings').doc(buildingID).collection('rooms').doc(roomID).collection('objects').doc(objectID).update(updatedTask);
window.addEventListener("DOMContentLoaded", async (e) => {
id = doc.id;
editStatus = true;
btnsEdit.forEach((btn) => {
btn.addEventListener("click", async (e) => {
try {
const doc = await getTask(e.target.dataset.id);
const task = doc.data();
editStatus = true;
id = doc.id;
taskformWindow["btn-update-data"].innerText = "Update";
} catch (error) {
console.log(error);
}
});
});
});
taskformWindow.addEventListener("click", async (e) => {
e.preventDefault();
var name_Window = document.getElementById('name_Window').value;
var wAluminium = document.getElementById('wAluminium').checked;
var wColorMeasurement = document.getElementById('wColorMeasurement').value;
var wComments = document.getElementById('wComments').value;
var wForEnd1 = document.getElementById('wForEnd1').checked;
var wForEnd2 = document.getElementById('wForEnd2').checked;
var wSideOfWindows = document.getElementById('wSideOfWindows').value;
var wHardwareManufacturer = document.getElementById('wHardwareManufacturer').value;
var wPlastic = document.getElementById('wPlastic').checked;
//Side 1
var wAxis1_1 = document.getElementById('wAxis1_1').checked;
var wAxis1_2 = document.getElementById('wAxis1_2').checked;
var wBackSet1 = document.getElementById('wBackSet1').value;
var wDirectionLR1_1 = document.getElementById('wDirectionLR1_1').checked;
var wDirectionLR1_2 = document.getElementById('wDirectionLR1_2').checked;
var wHandleHeight1 = document.getElementById('wHandleHeight1').value;
var wOverlapWidth1 = document.getElementById('wOverlapWidth1').value;
var wSashRebateHeight1 = document.getElementById('wSashRebateHeight1').value;
var wSashRebateWidth1 = document.getElementById('wSashRebateWidth1').value;
//Side 2
var wAxis2_1 = document.getElementById('wAxis2_1').checked;
var wAxis2_2 = document.getElementById('wAxis2_2').checked;
var wBackSet2 = document.getElementById('wBackSet2').value;
var wDirectionLR2_1 = document.getElementById('wDirectionLR2_1').checked;
var wDirectionLR2_2 = document.getElementById('wDirectionLR2_2').checked;
var wHandleHeight2 = document.getElementById('wHandleHeight2').value;
var wOverlapWidth2 = document.getElementById('wOverlapWidth2').value;
var wSashRebateHeight2 = document.getElementById('wSashRebateHeight2').value;
var wSashRebateWidth2 = document.getElementById('wSashRebateWidth2').value;
//Side 3
var wAxis3_1 = document.getElementById('wAxis3_1').checked;
var wAxis3_2 = document.getElementById('wAxis3_2').checked;
var wBackSet3 = document.getElementById('wBackSet3').value;
var wDirectionLR3_1 = document.getElementById('wDirectionLR3_1').checked;
var wDirectionLR3_2 = document.getElementById('wDirectionLR3_2').checked;
var wHandleHeight3 = document.getElementById('wHandleHeight3').value;
var wOverlapWidth3 = document.getElementById('wOverlapWidth3').value;
var wSashRebateHeight3 = document.getElementById('wSashRebateHeight3').value;
var wSashRebateWidth3 = document.getElementById('wSashRebateWidth3').value;
//Side 4
var wAxis4_1 = document.getElementById('wAxis4_1').checked;
var wAxis4_2 = document.getElementById('wAxis4_2').checked;
var wBackSet4 = document.getElementById('wBackSet4').value;
var wDirectionLR4_1 = document.getElementById('wDirectionLR4_1').checked;
var wDirectionLR4_2 = document.getElementById('wDirectionLR4_2').checked;
var wHandleHeight4 = document.getElementById('wHandleHeight4').value;
var wOverlapWidth4 = document.getElementById('wOverlapWidth4').value;
var wSashRebateHeight4 = document.getElementById('wSashRebateHeight4').value;
var wSashRebateWidth4 = document.getElementById('wSashRebateWidth4').value;
try {
if (!editStatus) {
await updateTask(id, {
name:name_Window,
Form:{
wAluminium: wAluminium,
wColorMeasurement: wColorMeasurement,
wComments: wComments,
wForEnd1: wForEnd1,
wForEnd2: wForEnd2,
wHardwareManufacturer: wHardwareManufacturer,
wPlastic: wPlastic,
wSide1:{
wAxis1_1: wAxis1_1,
wAxis1_2: wAxis1_2,
wBackSet1: wBackSet1,
wDirectionLR1_1: wDirectionLR1_1,
wDirectionLR1_2: wDirectionLR1_2,
wHandleHeight1: wHandleHeight1,
wOverlapWidth1: wOverlapWidth1,
wSashRebateHeight1: wSashRebateHeight1,
wSashRebateWidth1: wSashRebateWidth1,
},
wSide2:{
wAxis2_1: wAxis2_1,
wAxis2_2: wAxis2_2,
wBackSet1: wBackSet2,
wDirectionLR2_1: wDirectionLR2_1,
wDirectionLR2_2: wDirectionLR2_2,
wHandleHeight2: wHandleHeight2,
wOverlapWidth2: wOverlapWidth2,
wSashRebateHeight2: wSashRebateHeight2,
wSashRebateWidth2: wSashRebateWidth2,
},
wSide3:{
wAxis3_1: wAxis3_1,
wAxis3_2: wAxis3_2,
wBackSet1: wBackSet3,
wDirectionLR3_1: wDirectionLR3_1,
wDirectionLR3_2: wDirectionLR3_2,
wHandleHeight3: wHandleHeight3,
wOverlapWidth3: wOverlapWidth3,
wSashRebateHeight3: wSashRebateHeight3,
wSashRebateWidth3: wSashRebateWidth3,
},
wSide4:{
wAxis4_1: wAxis4_1,
wAxis4_2: wAxis4_2,
wBackSet4: wBackSet4,
wDirectionLR4_1: wDirectionLR4_1,
wDirectionLR4_2: wDirectionLR4_2,
wHandleHeight4: wHandleHeight4,
wOverlapWidth4: wOverlapWidth4,
wSashRebateHeight4: wSashRebateHeight4,
wSashRebateWidth4: wSashRebateWidth4,
},
wSideOfWindows: wSideOfWindows,
}
})
editStatus = false;
id = '';
taskformWindow['btn-update-window-data'].innerText = 'Daten aktualisiert';
swal("", "Daten wurden aktualisert!", "success");
}
taskformWindow.reset();
} catch (error) {
console.log(error);
}
});
}
I can't see the code you use for updating your data but I can ausme that you probably did not set the merge to true while saving the data.
Take a look at this code snipped:
var cityRef = db.collection('cities').doc('BJ');
var setWithMerge = cityRef.set({
capital: true
}, { merge: true });
By setting that we ensure to udate only the fields we want to and leave the rest as it is. Still make sure not to send fields with a null value because that is a valid value for firestore and it doesn't mean that those fields will by skipped in the update process. You can find more about it here.

Javascript I can take Filelist but I cant take file

I want take file from filelist but I cant take. How can I make
FileList (inputs[key].files)
FileList (inputs[key].files[0])
var inputs;
inputs = document.getElementsByTagName('input');
inputs = Array.prototype.slice.call(inputs);
var buttons = document.getElementsByTagName("button");
var buttonsCount = buttons.length;
for (var i = 0; i <= buttonsCount; i += 1) {
buttons[i].onclick = function(e) {
var userid = document.querySelector('.userid').innerHTML;
var raffleid = this.id;
var finish = this.value;
if (finish) {
postFinish(userid, raffleid, finish)
}
for (var key in inputs) {
var value = inputs[key].value;
var file = inputs[key].files;
var name = inputs[key].name;
if (value) {
console.log('file: ', file)
postData(raffleid, name, value, userid, file)
}
}
};
}
If I understand correctly, your code is working and you just want to access the Object?
Then try this:
const myArray = Object.values(FileList)
This returns an array of Objects, which you could access with
myArray[0]

How to change default var value in javascript on hover over piechart d3JS

I have a global var country = "Scotland"
and I have a method which takes the value in var country and sets it:
function isScottish(grant){
return grant.organisation.Country === country;
}
I have one callback function called ph which is called on hover over piechart.
var ph = function(d,i){
var DOMelement = this;
var fill = DOMelement.getAttribute("fill");
country="England"; // on hover set country to "England"
console.log(fill);
bc1.colour(fill);
bc1.render();
}
I tried like above but I am unable to set the country = "England".
Full Code :
"strict"
//Globals (so that we can inspect easily in the console)
var dataset1 = [];
var country = "Scotland";
var result = [];
var url = "data.json";
d3.json(url, function(error, jsonData) {
if (error) return userUpdate("Failed attepting to load JSON from :" + url);
processData(jsonData);
});
var scottishGrants; //use global so that we can inspect via console
function processData(jsonData){
dataset1 = jsonData;
//console.log(dataset1);
//Flatten database by adding a pointer to a grant's organisation obj
//in each grant obj
dataset1.grants.forEach(function(grant){
grant.organisation = getOrgByID(grant.OrgID);
})
scottishGrants = dataset1.grants.filter(isScottish)
console.log(scottishGrants);
//Of course we could make this more general by
//obtaining a list of countries (output to console)
var countries = {};
dataset1.organisations.forEach(function(org)
{
//Saves list of countries in countries array object as true
countries[org.Country]=true
})
var countryList = [];
//Key = Country and Value = True
//So therefore loop through countries array object and get keys to push in countryList array.
for (var key in countries) countryList.push(key);
console.log(countries);
console.log ("countryList = "+countryList);
//And then using this list to return a table of grants for each country
result = Array.from(
dataset1.grants.reduce((countries, grant) =>
countries.set(grant.organisation.Country,
(countries.get(grant.organisation.Country) || 0) + +grant.Value),
new Map()),
([country, sum]) => ({country,sum})
);
console.log(result);
}
function getOrgByID(ID){
var organisation=dataset1.organisations.find(function(org){
return org.OrgID === ID
})
return organisation
}
function isScottish(grant){
//return grant.organisation.Country === country;
return grant.organisation.Country === country;
}
//Set up a data generator and initialise with 6 values
var dg1 = dataGenerator(6); <!-- Generates the data and is stored in dg1 variable -->
// console.log(sourceDataset1);
//Create rendering objects
//var chart1 = barchart("#chart1DIV");
var bc1 = barchart("#bc1Div")
var pie1 = piechart("#p1")
.height(300)
.width(300);
//Render for the first time
var ph = function(d, i){
var DOMelement = this;
var fill = DOMelement.getAttribute("fill");
//var countryName = DOMelement.getAttribute("Country");
country="England";
console.log(fill);
bc1.colour(fill);
bc1.render();
}
function render(ds){
pie1.loadAndRenderDataset(ds);
rr1 = rawRenderer("#rr1")
.loadAndRender(ds);
layOutData = rawRenderer("#layoutData1")
.loadAndRender(pie1.layoutData());
bc1.loadDataset(scottishGrants)
.colour("red")
.render();
/*
chart1
.loadDataset(dg1.dataset())
.colour("PaleGreen")
.render();*/
}
pie1.pieOverCallback(ph);

How to empty an Array in a Script

I have a script that uses AJAX/PHP/SQL to query data and pushes it into an array with a bunch of IF's statements. The changeData function is called every 6 seconds. The first query I return I have 6 arrays. The second time i send a request, my push array(IsVacant1) is double and went to 12. after a while, I have over 500 arrays going into my .each statement.
How do I 'clear' this every time I make a request so that I am not adding arrays? Any help is most appreciated.
function changeData() {
isPaused = true;
var mydata0 = null;
$.post('php/ProductionChange.php', {
'WC': cc
}, function(data) { // This is Where I use an AJAX call into a php file.
mydata0 = data; // This takes the array from the call and puts it into a variable
var pa = JSON.parse(mydata0); // This parses the data into arrays and elements
var temp = {};
var bayData = '';
if (pa != null) {
for (var i = 0; i <= pa.length - 1; i++) {
var job = pa[i][0];
var shipdate = pa[i][1];
var status = pa[i][2];
var name = pa[i][3];
var EnclLoc = pa[i][13];
var Enclsize = pa[i][14];
var backpan = pa[i][15];
var percentCom = pa[i][16];
var IsVisible = pa[i][17];
var png = pa[i][18];
var WorkC = pa[i][20];
baydata = 'bayData' + i + '';
temp = {
job, shipdate, name, EnclLoc, Enclsize, backpan, percentCom, IsVisible, png, WorkC, status
};
isVacant1.push({
baydata: temp
});
}
} else {
ii = 1;
//alert("There are no more job numbers in this bay location. Thank you. ");
}
$.each(isVacant1, function(key, value) {
var job = value.baydata.job;
var ship = value.baydata.shipdate;
var name = value.baydata.name;
var encl = value.baydata.EnclLoc;
var EnclSize = value.baydata.EnclLoc;
var percentCom = value.baydata.percentCom;
var backpan = value.baydata.backpan;
var PngLogo = value.baydata.png;
var IsVisible = value.baydata.IsVisible;
var WorkC = value.baydata.WorkC;
var status = value.baydata.status;
var p = WorkC;
WorkC = (WorkC < 10) ? ("0" + WorkC) : WorkC;
//// remember if the encl location matches the workcell cell then do stuff based on that....... hint encl image not hiding becase of duplicate 17s
if (((encl == p) || (backpan == p)) && job != 123) {
$('#WC' + p).show();
document.getElementById("bayData" + p).innerHTML = name + ' ' + ship; // Work Cell Name and Ship Date
document.getElementById("bayData" + p + "a").innerHTML = job; // Work cell Job Number
document.getElementById("percentCom" + p).innerHTML = percentCom + '%'; // Work Cell Percent Complete
} else {
$('#WC' + p).hide();
From your question it looks like you want to clear the isVacant1 array.
In your ajax callback just put isVacant1 = []; as the first line. Like this
function(data) { // This is Where I use an AJAX call into a php file.
isVacant1 = [];
mydata0 = data; // This takes the array from the call and puts it into a variable
var pa = JSON.parse(mydata0); // This parses the data into arrays and elements
var temp = {};
var bayData = '';
..................
From your code it's not clear how you are declaring/initializing isVacant1 so i have suggested isVacant1 = [] otherwise you can also use isVacant1.length = 0.
You can also take a look here How do I empty an array in JavaScript?

How can I append json data if object key is equal to a predefined value?

I have got an ajax GET request that pulls in data through a loop. What I am trying to achieve is to get posts that are relevant but are not in the predefined id value of the current post you are on. So I have this function below:
var _permId = $('#work-area').data('current-id');
var getRelatedPosts = function() {
$.ajax({
url: '/wp-json/posts?type=case-studies&filter[taxonomy]=awards&filter[term]='+_awardsPart+'',
success: function ( query ) {
//List some global variables here to fetch post data
// We use base as our global object to find resources we need
// _permId is the var that tells me the current id of this post
var posts = query;
postFull = [];
for(var i = 0; i < posts.length; i++) {
//terms.push(term);
var postObject = posts[i];
postFull.push(postObject);
for (var key in postObject) {
//console.log(postObject[key]);
if (postObject[key] === _permId) {
console.log('this is the same as this post');
}
}
};
},
cache: false
});
};
What I want to do is not allow any content through if the post object id is the same value as _permId.
Here is an idea of the json that is retrieved with keys and values:
Object {ID: 4434, title: "new brand case", status: "publish", type: "case-studies", author: Object…}
The ID is the value I want to set an argument against.
You haven't to loop on the object if you just want to check the ID :
...
postFull = [];
for(var i = 0; i < posts.length; i++) {
var postObject = posts[i];
postFull.push(postObject);
if(postObject.ID === _permId) {
//they have the same id
}
};
EDIT :
To get the datas you want you can use $.grep :
var newArray = $.grep(posts, function(e, i){return e.ID !== _permiId;});
or in pure JS
var newArray = [];
for(var i = 0; i < posts.length; i++){
var p = posts[i];
if(p.ID !== _permId){
newArray.push(p);
}
}

Categories

Resources