Firebase - Generate table from database data - javascript

I would like to know how to create a table like thisfrom some data in a firebase database like this
There would need to be a column for ID, Title, Number of Answers, Correct Answer and Type. Preferably this should be done using jQuery.
Thank you in advance.

Get data
Read the firebase database documentation and references.
The basic firebase read operation looks like this:
var ref = firebase.database().ref("location");
ref.once("value")
.then(function(snapshot) {
var key = snapshot.key;
var value = snapshot.val();
console.log(key + ": " + value);
});
Of course you have to add scripts for firebase and firebase database before.
If you want to loop through an data you can use forEach function, for example:
var query = firebase.database().ref("location2");
query.once("value").then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var key = childSnapshot.key;
var value = childSnapshot.val();
console.log(key + ": " + value);
});
});
Table
You can create table dynamically using JS - functions like createElement and createDocumentFragment
For example:
var fragment = document.createDocumentFragment();
var animalsArray = ["Elephant", "Dog", "Cat"];
var table = document.createElement("table");
for (var i = 0; i < animalsArray.length; i++) {
var tr = document.createElement("tr");
var td = document.createElement("td");
td.textContent = animalsArray[i];
tr.appendChild(td);
table.appendChild(tr);
}
fragment.appendChild(table);
document.body.appendChild(fragment);
Table built from data in Firebase database
And now connect concepts above together. Create a table. Get data from firebase database. At every ireration over this data: create new table row with cells built from key and value of an element. In example below I used for loop to not duplicate the same operation for every cell.
Full example:
Data tree in Firebase Database:
{
"location2" : {
"hello" : "world",
"hi" : "Mark"
}
}
Code:
var fragment = document.createDocumentFragment();
var table = document.createElement("table");
var query = firebase.database().ref("location2");
query.once("value").then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var tr = document.createElement("tr");
var trValues = [childSnapshot.key, childSnapshot.val()];
for (var i = 0; i < trValues.length; i++) {
var td = document.createElement("td");
td.textContent = trValues[i];
tr.appendChild(td);
}
table.appendChild(tr);
});
});
fragment.appendChild(table);
document.body.appendChild(fragment);

Related

How to get Value from Firebase and add in HTML Table using JavaScript

I'm trying to get loggedin Used Data from firebase and add show into HTML Table
this is my database structure"
{
"attendance": {
"7-----------asdasdasd-----": {
"2023-1-9": {
"status": "success"
}
},
}
}
I'm simply tring to get value date and status value from firebase make table in html to show data.
I'm able to login user using firebase auth google. and able to post value aswell. just not able to get value correctly and show in table.
Here is what i tried to get value from firebase and add into html table:
// Get the table element
var table = document.getElementById("attendance-table");
// Handle auth state changes
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in
var userId = firebase.auth().currentUser.uid;
firebase.database().ref("attendance/" + userId).on("value", function(snapshot) {
// Clear the table
table.innerHTML = "";
// Get the attendance data
var attendanceData = snapshot.val();
var attendanceKeys = Object.keys(attendanceData);
// Add a row to the table for each attendance record
for (var i = 0; i < attendanceKeys.length; i++) {
var date = attendanceKeys[i];
var status = attendanceData[attendanceKeys[i]].status;
var row = document.createElement("tr");
var dateCell = document.createElement("td");
var statusCell = document.createElement("td");
dateCell.innerHTML = date;
statusCell.innerHTML = status;
row.appendChild(dateCell);
row.appendChild(statusCell);
table.appendChild(row);
}
});
}
});
<table id="attendance-table">
<thead>
<tr>
<th>Date</th>
<th>Status</th>
</tr>
</thead>
<tbody id="attendance-table-body"></tbody>
<tfoot></tfoot>
</table>
Got the Solutions now it Worked!
Here is Script Changes:
<script>
// Get the table element
var table = document.getElementById("attendance-table");
// Handle auth state changes
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in
var userId = firebase.auth().currentUser.uid;
firebase.database().ref("attendance/" + userId).once("value", function(snapshot) {
// Clear the table
table.innerHTML = "";
// Get the attendance data
var attendanceData = snapshot.val();
var attendanceKeys = Object.keys(attendanceData);
// Add a row to the table for each attendance record
for (var i = 0; i < attendanceKeys.length; i++) {
var date = attendanceKeys[i];
var status = attendanceData[attendanceKeys[i]].status;
var row = document.createElement("tr");
var dateCell = document.createElement("td");
var statusCell = document.createElement("td");
dateCell.innerHTML = date;
statusCell.innerHTML = status;
row.appendChild(dateCell);
row.appendChild(statusCell);
table.appendChild(row);
}
});
}
});
</script>

how to get json using javascript?

json data example
{
"CPU Running": {
"user": "Yama/Rayno",
"container": [
"C-23-1",
"C-24-1",
"C-40-1"
]
},
"Nonstop CPU": {
"user": "Kang/Yoon",
"container": [
"C-25-1",
"C-26-1",
"C-31-1",
"C-32-1",
"C-33-1",
"C-34-1",
"C-37-1",
"C-38-1"
]
}
i use this script
but change ${data[i].job} row
for (i = 0; i < data.length; i++) {
if (data[i].container != null) {
var add_data = `<tr>
<td>
${data[i].container}
</td>
<td>
${data[i].user}
</td>
<td>
${data[i].job}
</td>
</tr>`;
how to output this format?
CPU Running, Nonstop CPU as Job name
what calling this space in json?
First of all, you json data is incomplete. An additional } should be added at the end of your data.
I am not writing a full solution, rather showing how you can access your data.
Getting CPU Running data, This is an object, containing another two fields: user and an list-container.
So access the CPU-Running event like this:
var cpuRunner= yourJsonData["CPU Running"]; //assuming `yourJsonData` holds your json data
var cpuRunnerUser= cpuRunner["user"];
var containerList= cpuRunner["container"]; //this is your container list for cpu-running
Now, iterate on this containerList for your html for cpuRunning containers
Similarly,
you can get the container list for Nonstop CPU too
inside of html page select place for your table, and add table style to css or just put in the html page header
<p id="showData"></p>
and this is a javascript code
function CreateTableFromJSON(obj) {
// CREATE DYNAMIC TABLE.
var table = document.createElement("table");
// ADD JSON DATA TO THE TABLE AS ROWS.
iterateData(obj, table);
// FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
}
function iterateData(obj, table) {
Object.keys(obj).forEach((key) => {
if (typeof obj[key] === "object") {
var tr = table.insertRow(-1);
var tabCell1 = tr.insertCell(-1);
if (key == "container") tabCell1.innerHTML = key;
else {
tabCell1.innerHTML = "Job";
var tabCell2 = tr.insertCell(-1);
tabCell2.innerHTML = key;
}
iterateData(obj[key], table);
}
tr = table.insertRow(-1);
if (key == "user") {
var tabCell1 = tr.insertCell(-1);
tabCell1.innerHTML = key;
}
if (typeof obj[key] == "string") {
var tabCell2 = tr.insertCell(-1);
tabCell2.innerHTML = obj[key];
}
});
}

how to create "href" using JavaScript of a google drive file

I have a dynamic table created using JavaScript my dataArray consist of many information including drive file downloadable link example :-
dataArray[i][4] has google file dowanload link = drive.google.com/uc?export=download&id=1YH6xxxxxxxxxxxxxxxphUl
Now I can't create a downloadable link using the url field of my dataset I tried following:-
function getreferData(dataArray)
{
var ray = dataArray.splice(0,1)
let table = document.getElementById('thead1');
var tableHeaderRow = document.createElement("tr");
table.appendChild(tableHeaderRow);
for(i=0;i<ray[0].length;i++){
var tableHeader = document.createElement("th");
tableHeaderRow.appendChild(tableHeader);
tableHeader.innerHTML = ray[0][i];
}
let tbody = document.getElementById('perf');
for (var i=0;i<dataArray.length;i++)
{
let row = document.createElement("tr")
for (var j=0;j<dataArray[i].length;j++)
{
if (j==4)
{
let col = document.createElement("td")
var a = document.createElement("a");
a.href = "/'"+dataArray[i][j]+"/'";
var node = document.createTextNode("Click here")
a.appendChild(node)
col.appendChild(a)
row.appendChild(col)
}
else
{
let col = document.createElement("td")
col.innerText = dataArray[i][j]
row.appendChild(col)
}
}
tbody.appendChild(row);
}
image of my array logs:-
I was able to get it worked by Adding "https://" in my link drive.google.com/uc?export=download&id=1YH6xxxxxxxxxxxxxxxphUl.

Remove a duplicate row in table when being added from an array?

I have something like this:
getELE("btnAddStudent").addEventListener("click", function(){
var ID = getELE("txtID").value;
var Name = getELE("txtName").value;
var Score = getELE("txtScore).value;
var St = new Student(ID, Name, Score);
List.Add(St);
var table = getELE("tbodyStudent");
for (var i = 0; i < List.arrSt.length; i++) {
var tr = document.createElement("tr");
for (var key of ['ID', 'Name', 'Score'])
{
var td = document.createElement("td");
td.innerHTML = List.arrSt[i][key];
tr.appendChild(td);
}
table.appendChild(tr);
}
});
The problem is whenever I add a new student, the table will add a whole list of students instead of adding just the new student to it making it have duplicate students.
How do I add just the new student instead of the whole list?
I have tried to tweak this into my "for" loop but still doesn't work.
Your code seems that you add whole list again to your table.
Here's updated code. Please try this.
getELE("btnAddStudent").addEventListener("click", function(){
var ID = getELE("txtID").value;
var Name = getELE("txtName").value;
var Score = getELE("txtScore).value;
var St = new Student(ID, Name, Score);
var table = getELE("tbodyStudent");
var tr = document.createElement("tr");
for (var key of ['ID', 'Name', 'Score'])
{
var td = document.createElement("td");
td.innerHTML = St[key];
tr.appendChild(td);
}
table.appendChild(tr);
List.Add(St);
});
The solution for this is add the tr when you are adding a new student.
var table = getELE("tbodyStudent");
var tr = document.createElement("tr");
for (var key of ['ID', 'Name', 'Score'])
{
var td = document.createElement("td");
// add here the new Student data
td.innerHTML = newStudentData[key];
tr.appendChild(td);
}
table.appendChild(tr);
I agree with above solution.
It is a good solution Adding a row when you add a new student.

How to add different columns to a dynamic table from database with javascript

I have a function building a dynamic table. I'm having trouble figuring out how to set each column to a different data set from the database. Right now it just shows the same value in each column.
A little background. I'm building a table with 6 columns and lots of rows (all depends how much data the database has). Right now it's only showing one column in all of the 6 columns, so they repeat.
How can I set each column to a different value for the 6 columns?
function addTable() {
var len = errorTableData.length;
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
table.border='1';
table.id = "dataTable";
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var i=0; i<len; i++){
var tr = document.createElement('TR');
tr.className = "rowEditData";
tableBody.appendChild(tr);
for (var j=0; j<6; j++){
var countyName = errorTableData['CountyName'][i];
var stateName = errorTableData['StateName'][i];
var td = document.createElement('TD');
td.className = "mdl-data-table__cell--non-numeric";
td.appendChild(document.createTextNode(countyName));
td.appendChild(document.createTextNode(stateName));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
Here is the ajax call:
function triggerDataTable(index) {
// Make AJAX requests for model systems
$.ajax({
type: "POST",
url: "qry/getAllData.php",
async: true,
dataType: "html",
data: {ErrorOptions: control.settings.errorOptions},
success: function (result) {
//console.warn(result);
errorData = JSON.parse(result);
//loop through data
var len = errorData.length;
for(i=0; i<len; i++) {
if ('VersionKey' in errorData[i]) {
vKey = (errorData[i]['VersionKey']);
} else if ('ErrorCode' in errorData[i]) {
var errorCode = (errorData[i]['ErrorCode']);
} else if ('SourceKey' in errorData[i]) {
var sourceKey = (errorData[i]['SourceKey']);
} else { //data here
errorTableData = errorData[i];
}
}
addTable();
}
});
}
The errorData is the data from the database. As you can see I've tried to add 2 variables but when I do that it just puts both of them in the same box and repeats throughout the whole table.
It looks like you are printing the exact same data 6 times for each row. You create a td element, then add country and state names to it, but the variable you are using for the index on your data set is coming from your outer loop, so on the inner loop it never changes, and you are literally grabbing the same value every time:
function addTable() {
var len = errorTableData.length;
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
table.border='1';
table.id = "dataTable";
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var i=0; i<len; i++){
// You set i here, presumably to get each row in your dataset
var tr = document.createElement('TR');
tr.className = "rowEditData";
tableBody.appendChild(tr);
for (var j=0; j<6; j++){
var countyName = errorTableData['CountyName'][i];
var stateName = errorTableData['StateName'][i];
// Above, you are using i, not j
var td = document.createElement('TD');
td.className = "mdl-data-table__cell--non-numeric";
td.appendChild(document.createTextNode(countyName));
td.appendChild(document.createTextNode(stateName));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
It would be easier to help if you could post some json with the data you are getting from the DB
Based on the edit on your post and looking at the success callback, I think you have small problem that can be easily fixed:
First, initialize an empty array for errorTableData
success: function (result) {
errorTableData = [];
In your if/else block:
} else { //data here
errorTableData = errorData[i];
}
Should be:
} else { //data here
errorTableData[i] = errorData[i];
}
Then in your inner loop:
var countyName = errorTableData['CountyName'][i];
var stateName = errorTableData['StateName'][i];
Becomes:
var countyName = errorTableData[i]['CountyName'][j];
var stateName = errorTableData[i]['StateName'][j];
This is just a guess because I can't see the actual data.

Categories