We are trying to retrieve data from a nested parent child relationship from realtime database from firebase using javascript (Html). Below is the code we are using and output, but the section of where there is nested data we are getting [object, Object] and undefined. We get the desired output on the console but not on the webpage.
const db = getDatabase();
var tablebody = document.getElementById('assQuestions');
var asspool = [];
function addassquesvalues(quescat,quesid,queslaws,lawname,statements,question){
let trow=document.createElement('tr');
let td1=document.createElement('td');
let td2=document.createElement('td');
let td3=document.createElement('td');
let td4=document.createElement('td');
let td5=document.createElement('td');
let td6=document.createElement('td');
asspool.push(quescat,question,queslaws);
td1.innerHTML = quescat;
td2.innerHTML = quesid;
td3.innerHTML = queslaws;
td4.innerHTML = lawname;
td5.innerHTML = statements;
td6.innerHTML = question;
trow.appendChild(td1);
trow.appendChild(td2);
trow.appendChild(td3);
trow.appendChild(td4);
trow.appendChild(td5);
trow.appendChild(td6);
tablebody.appendChild(trow);
console.log(queslaws)
}
function addassquesvaluestotable(questions){
tablebody.innerHTML="";
questions.forEach(element=>{
addassquesvalues(element.quescat, element.quesid, element.queslaws, element.lawname, element.statements, element.question);
})
}
function getdatarealtime(){
const dbref=ref(db,"AssessmentQues");
onValue(dbref,(snapshot)=>{
var allassques = [];
snapshot.forEach(childSnapshot => {
allassques.push(childSnapshot.val());
});
addassquesvaluestotable(allassques);
})
}
window.onload = getdatarealtime;
Output in form of a table
Related
I am trying to pass information from an API call into an HTML table which I can then also use for graphs. A picture of the array is attached to show the data structure. I keep receiving an error that column_names is not iterable but I have not been able to work it out after hours of searching. I think it has to do with the names in my array but can't find a solution. I'm new to this and I feel like the answer is painfully simple so any help or explanation of my error would be appreciated.
Array Format
async function loadintotable(url, table) {
const tableHead = table.querySelector('thead');
const tableBody = table.querySelector('tbody');
const response = await fetch(url);
const { column_names, data } = await response.json();
tableHead.innerHTML = '<tr></tr>';
tableBody.innerHTML = '';
for (const headerText of column_names) {
const headerElement = document.createElement('th');
headerElement.textContent = headerText;
tableHead.querySelector('tr').appendChild(headerElement);
}
for (const row of data) {
const rowElement = document.createElement('tr');
for (const cellText of row) {
const cellElement = document.createElement('td');
cellElement.textContent = cellText;
rowElement.appendChild(cellElement);
}
tableBody.appendChild(rowElement);
}
}
Your api response is of format
{
dataset: {
column_names: [],
data: []
}
}
So, in order to access column_names and data you have to
const json = await response.json();
const { column_names, data } = json.dataset;
Or in one line
const { column_names, data } = (await response.json()).dataset;
Notice the .dataset at the end of the line
In a course I'm taking my lecturer wrote the below code for submitting data from a form when the submit button is pressed. It stores this to sessionStorage and then renders the received messages below the form. I made sure to copy it exactly and mine doesn't work. It seems to be because the .fullName, .email, .feedbackType and .comment are not being assigned a type. When I ran the lecturers code file from my vscode and checked it in the browser his worked fine. My work is identical to his bar some different CSS styles. It is currently just putting undefined for each item
function submitMessage(event) {
event.preventDefault();
const email = document.getElementById('email').value;
const fullName = document.getElementById('fullName').value;
const feedbackType = document.getElementById('feedbackType').value;
const comment = document.getElementById('comment').value;
const messageObject = {
email,
fullName,
feedbackType,
comment,
};
let currentMessages = [];
if (window.sessionStorage.getItem('messages')) {
currentMessages = JSON.parse(
window.sessionStorage.getItem('messages')
);
}
currentMessages.push({
messageObject
});
/*temporary fix, find a solution for this error, .push not working/recognised. Code matching lectures is currentMessages.push(messageObject)*/
window.sessionStorage.setItem(
'messages',
JSON.stringify(currentMessages)
);
renderMessages();
}
function renderMessages() {
let currentMessages = [];
if (window.sessionStorage.getItem("messages")) {
currentMessages =
JSON.parse(
window.sessionStorage.getItem("messages")
);
}
let listItems = [];
for (let i = 0; i < currentMessages.length; i++) {
let listItem = " ";
const currentMessage = currentMessages[i];
listItem += `<dt>${currentMessage.fullName} - ${currentMessage.email}</dt>`;
listItem += `<dd>${currentMessage.feedbackType}: ${currentMessage.comment}</dd>`;
listItem += `<br />`;
listItems.push(listItem);
}
let descList = document.getElementById('currentMessages');
descList.innerHTML = listItems.join('');
}
renderMessages();
I am trying to alter a object variable after query in cloud functions, but before sending it to my app, but not sure how to do so! Here is what I am trying to do:
Parse.Cloud.define("getUserData", async(request) => {
// Getting the users data
const userQuery = new Parse.Query("UserData");
userQuery.equalTo("userId", request.params.userId);
const userData = await userQuery.first();
// Getting the groups
const groupQuery = new Parse.Query("GroupMembers");
groupQuery.equalTo("userId", request.params.userId);
groupQuery.include('pointerObject'); // including the pointer object
const groups = await groupQuery.find();
const allGroups = [];
for (let i = 0; i < groups.length; ++i) {
var thisGroup = groups[i].get("pointerObject");
thisGroup.isFavorite = true;
allGroups.push(thisGroup);
}
var returnObject = {
"playerData": userData,
"playerGroups": allGroups
}
const jsonString = JSON.stringify(returnObject);
return jsonString;
});
It is "thisGroup.isFavorite" i am trying to set to true, but when receiving the jsonString, it is still set to false? How do I alter a variable in cloud functions?
Any help is appreciated and thanks in advance :-)
Try with:
thisGroup.set('isFavorite', true);
await thisGroup.save();
I am using an API from Caspio to import a Data Table that will be variable.
for that, I am doing the following
<script type="text/javascript" id='Test' src="https://c1afw487.caspio.com/dp/6e444000877ca58e63624b0b8c78/emb"></script>
and then to format it (send it to the bottom of my web page) I am doing this:
<div id='InfoTable' style='width: 40%; float: left;'>
<a id='TestTwo' href="https://c1afw487.caspio.com/dp/6e444000877ca58e63624b0b8c78">DataTable </a>
</div>
Now, I am trying to access the data from the table. For that I am trying something like this
var DataTest = document.getElementById('Test');
var DataTestTwo = document.getElementById('TestTwo');
console.log(JSON.stringify(DataTest));
console.log(JSON.stringify(DataTestTwo));
But the first test returns { } and the second one null (notice how I tried to give an ID to the imported table so I could access it but any of my attempts worked).
What is the proper way to access the Table?
I dont know anything about that specific API but quick google seems to suggest that they have a separate rest api for requesting JSON data. You should look into that.
Stringifying an html element does nothing usefull...its an html element not your request payload data.
You can go over the table itself and extract all the contents into a json.
Something like this.
https://jsfiddle.net/rainerpl/wvdoek03/14/
var getHeaders = (table) => {
const headerRow = table.tBodies[0].children[0];
const headers = [];
let i;
for (i = 0; i < headerRow.children.length; i++) {
headers.push(headerRow.children[i].innerText);
}
return headers;
}
var getData = (table) => {
const data = [];
let i;
for (i = 1; i < table.tBodies[0].children.length; i++) {
let newDataRow = [];
for (j = 0; j < table.tBodies[0].children[i].children.length; j++) {
newDataRow.push(table.tBodies[0].children[i].children[j].innerText);
}
data.push(newDataRow);
}
return data;
}
JsonTable = function() {
const table = document.getElementsByTagName('table')[0];
const headers = getHeaders(table);
const data = getData(table);
this.getRow = (rowNr) => {
const result = {};
headers.forEach((key, index) => {
result[key] = data[rowNr][index];
});
return result;
}
console.log('table', table, 'has data:', data, ' and headers ', headers);
}
const jsonTable = new JsonTable();
console.log('First row is', jsonTable.getRow(0));
console.log('Second row is', jsonTable.getRow(1));
You can view the console output on jsFiddle to see what it looks like.
( use inspect developer tool to see console output )
I'm able to display the correct data from my Firebase child in the console with the following code:
var ref = firebase.database().ref('requests');
ref.on('value', gotData, errData);
function gotData(data) {
var scores = data.val();
console.log(scores);
}
Which displays the following in the console:
So when I try to use this snippet of code to retrieve the email:
function gotData(data) {
var scores = data.val();
console.log(scores);
var keys = Object.keys(Email);
console.log(keys);
for (var i = 0; i < keys.length; i++) {
var k = keys[i];
var emails = email[k].email;
console.log(emails);
}
}
it's displaying the following error:
but I'm not fully understanding why I'm getting this error when this is very similar to other peoples solution.
Anyone know why I'm getting this error when there is an actual value for the email key?
To get the email simply to do this:
var ref = firebase.database().ref('requests');
ref.on('value', function(snapshot) {
snapshot.forEach(function(child) {
var datas = child.val();
var email=child.val().Email;
});
});
Assuming you have this database:
requests
randomid
Email: email_here
You need to be iterating inside the randomid to be able to access the property Email