Display data from firebase to HTML table - javascript

I would like to ask some help, I'm a front-end developer and we currently have a project/task that is all about the back end. My team members decided to used firebase as a database in our web application. I can now send data to the database but I have a problem, I cant retrieve the data from firebase to the web application. I am planning to retrieve data and display it in my table (HTML).
This is my code in my javascript for retrieving data from firebase:
var database = firebase.database().ref().child('Tasks');
database.once('value', function(snapshot){
if(snapshot.exists()){
var content = '';
var TaskTitle = snapshot.val().TaskTitle;
var JobId= snapshot.val().JobId;
snapshot.forEach(function(data){
});
content = '<tr>';
content += '<td>' + TaskTitle + '</td>'; //column1
content += '<td>' + JobId + '</td>';//column2
content += '</tr>';
}
$('#ex-table').append(content);
console.log(snapshot.val());
});
And this is my code in my HTML table to display the data from the database:
<table class="table table-striped" id="ex-table">
<thead class="thead-inverse">
<tr>
<th>Task Title</th>
<th>Category</th>
<th>Date</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr id="tr">
<td id="titleTask"></td>
<td id="categoryTask"></td>
<td id="dateTask"></td>
<td id="statusTask"></td>
</tr>
</tbody>
I cant actually see the data that I have retrieved using the console in my web browser in chrome.
and it's displaying this: Data displayed in console while in my web app it's displaying like this: undefined
Can someone please help me, I'm new to everything your help is so much appreciated.

Your nesting is a bit wonky, and unfortunately it matters quite a lot where you put all the bits:
var database = firebase.database().ref().child('Tasks');
database.once('value', function(snapshot){
if(snapshot.exists()){
var content = '';
snapshot.forEach(function(data){
var TaskTitle = data.val().TaskTitle;
var JobId= data.val().JobId;
content += '<tr>';
content += '<td>' + TaskTitle + '</td>'; //column1
content += '<td>' + JobId + '</td>';//column2
content += '</tr>';
});
$('#ex-table').append(content);
}
});
In steps:
This loads the tasks from Firebase, with database.once().
Then if there are any tasks (one level indented), it loops over them (with snapshot.forEach(...)).
In that callback (so one more level indented) it takes the title and job id for that specific task, and adds it to the HTML string it is building.
The finally it adds the HTML to the table.

<table border="1" style="width:100%" id="ex-table">
<tr id="tr">
<th>Student ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Address</th>
<th>Username</th>
<th>Password</th>
</tr>
</table>
const starCountRef = ref(database, 'user_register/');
onValue(starCountRef, (snapshot) => {
snapshot.forEach(function (data) {
var val = data.val();
var content = '';
content += '<tr>';
content += '<td>' + val.student_id + '</td>'; //column1
content += '<td>' + val.first_name + '</td>';//column2
content += '<td>' + val.last_name + '</td>';//column2
content += '<td>' + val.email + '</td>'; //column1
content += '<td>' + val.address + '</td>';//column2
content += '<td>' + val.username + '</td>';//column2
content += '<td>' + val.password + '</td>';//column2
content += '</tr>';
$('#ex-table').append(content);
});
});

Related

JSON to HTML Table JavaScript Not Working

JSON to HTML Table JavaScript Not Working
I've written this function to display the contents of the JSON file in an HTML table. However, it's returning as undefined.
I don't seem to be able to work out why this is happening. The console log displays the data just fine, but not the HTML table.
I'm wondering if it has something to do with the way arrays are parsed?
I want to keep the code short and clean, but wondering if there is a better way to do this without the undefined error. Maybe Vanilla JavaScript is better, using fetch?
Live page is found here: LBRYnomics
Thanks in advance!
jQuery(document).ready(function($) { $.getJSON('https://www.brendonbrewer.com/lbrynomics/subscriber_counts.json', function(data) {
var humanTimeSub = `${data.human_time_utc}`
$(".human-time-sub").html(humanTimeSub)
var sub_data = '';
$.each(data, function(key, value) {
sub_data += '<tr>';
sub_data += '<td>' + value.ranks + '</td>';
sub_data += '<td>' + value.vanity_names + '</td>';
sub_data += '<td>' + value.claim_ids + '</td>';
sub_data += '<td>' + value.subscribers + '</td>';
sub_data += '</tr>';
console.log(key + '=' + value);
});
$('#sub-stats').append(sub_data);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="sub-stats">
<tr>
<th>RANK</th>
<th>VANITY NAME</th>
<th>CLAIM ID</th>
<th>SUBS</th>
</tr>
</table>
You have multiple different arrays for each of those properties.
Assuming they are all in same relationship order you can loop over one of the arrays and use the iteration index to access corresponding elements from each of the other arrays.
Something like:
jQuery(document).ready(function($) { $.getJSON('https://www.brendonbrewer.com/lbrynomics/subscriber_counts.json', function(data) {
var humanTimeSub = `${data.human_time_utc}`
$(".human-time-sub").html(humanTimeSub);
var sub_data = '';
$.each(data.ranks, function(i, rank) {
sub_data += '<tr>';
sub_data += '<td>' + rank + '</td>';
sub_data += '<td>' + data.vanity_names[i] + '</td>';
sub_data += '<td>' + data.claim_ids[i] + '</td>';
sub_data += '<td>' + data.subscribers[i] + '</td>';
sub_data += '</tr>';
//console.log(key + '=' + value);
});
$('#sub-stats').append(sub_data);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="sub-stats">
<tr>
<th>RANK</th>
<th>VANITY NAME</th>
<th>CLAIM ID</th>
<th>SUBS</th>
</tr>
</table>
I think after inspecting the api it looks the items are put in different array with no connection but they have the same length. So assuming that attrbute1 at index N maps to attribute2 at index N and so on.
jQuery(document).ready(function($) { $.getJSON('https://www.brendonbrewer.com/lbrynomics/subscriber_counts.json', function(data) {
var humanTimeSub = `${data.human_time_utc}`
$(".human-time-sub").html(humanTimeSub)
var sub_data = '';
for(var i=0; i<data.ranks.length; i++){
//$.each(data.ranks, function(key, value) {
sub_data += '<tr>';
sub_data += '<td>' + data.ranks[i] + '</td>';
sub_data += '<td>' + data.vanity_names[i] + '</td>';
sub_data += '<td>' + data.claim_ids[i] + '</td>';
sub_data += '<td>' + data.subscribers[i] + '</td>';
sub_data += '</tr>';
//console.log(key + '=' + value);
//});
}
$('#sub-stats').append(sub_data);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="sub-stats">
<tr>
<th>RANK</th>
<th>VANITY NAME</th>
<th>CLAIM ID</th>
<th>SUBS</th>
</tr>
</table>

How to append table>tr in table>tbody(already existing table) in javascript(working with Chrome extension)

I am working with chrome extension .My main problem is I am not
able to append my tr under tbody as the error occur and stating
"Cannot read property 'getElementsByTagName' of null". So how Do I
append this in chrome extension using javascript.
In background.js I have tried this:
response.json().then(function (data) {
var dResponse = data.results;
if (dResponse.length > 0) {
var tableRef = document.getElementsByTagName('tbody')[0];
for (var obj = 0; obj < dResponse.length; obj++) {
var result = '<tr>' +
'<td>' + dResponse[obj].title + '</td>' +
'<td>' + dResponse[obj].category_path + '</td>' +
'<td>' + dResponse[obj].price + '</td>' +
'<td>' + dResponse[obj].num_favorers + '</td>' +
'<td>' + dResponse[obj].tags + '</td>';
result += '</tr>';
var tableRef =
tableRef.appendChild(result);
console.log(result);
};
}
});
I am hitting API and and my response is under data.
When I console my result so as output tr is comming.
var tableRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];
var tableRef = document.getElementsByTagName('tbody')[0];
both lines are giving this "Cannot read property 'getElementsByTagName' error
I also tried other ways to append but everytime it gives same error.I am not getting why this is happening.
response.json().then(function (data) {
var dResponse = data.results;
if (dResponse.length > 0) {
var tableRef = document.getElementsByTagName('tbody')[0];
for (var obj = 0; obj < dResponse.length; obj++) {
var result = '<tr>' +
'<td>' + dResponse[obj].title + '</td>' +
'<td>' + dResponse[obj].category_path + '</td>' +
'<td>' + dResponse[obj].price + '</td>' +
'<td>' + dResponse[obj].num_favorers + '</td>' +
'<td>' + dResponse[obj].tags + '</td>';
result += '</tr>';
var tableRef =
tableRef.appendChild(result);
console.log(result);
};
}
});
```
```background.html```
<div class="table-responsive mb-0" data-toggle="lists">
<table class="table table-sm table-nowrap card-table" id="myTable">
<thead>
<tr>
<th>Product Name</th>
<th>Category</th>
<th>Price</th>
<th>Favourites</th>
<th>Tags</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
```
<script src="background.js"></script>
> I am getting error "Cannot read property 'getElementsByTagName' of null". I only want to append my tr under tbody
I think that your background.js executes before the page has loaded, You can't access the "tbody"
This is how to run background.js after page load.
<script>
function init(){
var tag = document.createElement("script");
tag.src = "background.js";
document.getElementsByTagName("head")[0].appendChild(tag);
}
</script>
<head></head>
<body onload='init()'>
<table><tbody><tbody></table>
</body>

How can I fetch the data in a single row

I am tying to fetch the data from firebase just like make single row of first element of all the headings in firebase database. i.e first element of Amount, key, time, total, Number should make a single row and then so on.
I am trying with foreach loop but I can refer to the correct refrence of firebase
//html code
<table style="width:100%" id="ex-table">
<tr id="tr">
<th>Amount</th>
<th>Key</th>
<th>Number</th>
<th>Time</th>
<th>Total</th>
</table>
//Javascript code
var database = firebase.database();
database.ref().once('value', function(snapshot){
if(snapshot.exists()){
var content = '';
snapshot.forEach(function(data){
var val = data.val();
content +='<tr>';
content += '<td>' + val.Amount + '</td>';
content += '<td>' + val.Key + '</td>';
content += '<td>' + val.Number + '</td>';
content += '<td>' + val.Time + '</td>';
content += '<td>' + val.Total + '</td>';
content += '</tr>';
});
$('#ex-table').append(content);
}
});
I am getting undefined instead of values

Appending variables in string definition

I'm trying to format a table of data as a string and return it to the page. I have the following, but I'm afraid this isn't a valid way to define my variable.
var tableOutput = ' <
table class = \"child-info\" cellpadding=\"5\" cellspacing=\"0\" border=\"0\" style=\"padding-left:50px;\">'+
'<tr>' +
'<td>Level:</td>' +
'<td>' + d.deg_codes[0] + '</td>' +
'</tr>' +
'<tr>' +
'<td>Level:</td>' +
'<td>' + d.deg_codes[1] + '</td>' +
'</tr>' +
'</table>';
return tableOutput;
However, it works when I just return the entire definition statement by itself. Unfortunately, I need it as a variable to be able to modify it. Is there a better way to define this? Or do I have to do a huge number of appends?
EDIT:
Got it working as:
var tableOutput = `
<table class = "child-info" cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">
<tr>
<td>Level USF Tampa:</td>
<td>${d.deg_codes[0]}</td>
</tr>
<tr>
<td>Level USF Tampa:</td>
<td>${d.deg_codes[1]}</td>
</tr>
</table>`;
Use javascript template strings
`string text line 1
string text line 2`
Also remove unnecessary quotes ' and + for concatenation
function showTable() {
const d = {
deg_codes: [3434, 4444]
};
var tableOutput = `<table class = "child-info" cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">
<tr>
<td>Level:</td>
<td>${d.deg_codes[0]}</td>
</tr>
<tr>
<td>Level:</td>
<td>${d.deg_codes[0]}</td>
</tr>
</table>`;
return tableOutput;
}
document.write(showTable());

Update table row with animation upon AJAX request

I'm creating a 'live' leaderboard table. Every X seconds, an AJAX request is sent to the server to load the latest leaderboard data.
If there's a change in data, the leaderboard will instantly update upon the AJAX request.
However - If there IS a change, instead of instantly showing the new data, I want to animate the table row to its new position instead of instantly reloading it. What is the best way of achieving something like this?
I'm updating the leaderboard at the moment like so:
$(document).ready(function() {
showLeaderboard();
if (autoUpdate != false) {
window.setInterval(function(){
$('#wrapper h2, #leaderboard tbody tr').remove(updateLeaderboard());
}, reloadInterval);
}
});
function updateLeaderboard() {
leaderBoardType;
numRecords;
quizIDs;
topListTitle;
latestTitle;
$.webMethod({
url: 'xxx',
data: '{quizIDs:"'+quizIDs+'",numRecords:"'+numRecords+'"}',
type: 'POST',
cache: false,
beforeSend: function () {
$('body').append('<div class="loading"></div>');
},
success: function (ret)
{
$('.loading').remove();
$('#wrapper').prepend(topListTitle);
$.each(ret.leaderboard,function(i){
pos = i + 1;
str = '<td class="position">' + pos + '</td>';
str += '<td class="name">' + ret.leaderboard[i].first_name + ' ' + ret.leaderboard[i].last_name + '</td>';
str += '<td class="time">' + getTime(ret.leaderboard[i].time_taken) + '</td>';
str += '<td class="points">' + ret.leaderboard[i].points + '</td>';
//str += '<td>' + ret.leaderboard[i].last_name + '</td>';
//str += '<td>' + ret.leaderboard[i].incorrect_attempts + '</td>';
//str += '<td>' + ret.leaderboard[i].user_id + '</td>';
$('#leaderboard tbody').append('<tr>'+str+'</tr>');
});
},
error: function (response) { alert(response.responseText); }
});
}
HTML
<table id="leaderboard">
<thead>
<tr>
<th class="position">Position</th>
<th class="name">Name</th>
<th class="time">Time Taken</th>
<th class="points">Points</th>
</tr>
</thead>
<tbody>
</tbody>
</table>

Categories