I am currently using Firebase to build a simple e-commerce website and have run into an issue. For the backend I am trying to populate an HTML table with Firebase database data.
Currently, the data is appearing and I am able to populate the body of the table, but at the same time I want to create the headers for the table using the same snapshot. I have been able to do this however it repeats for every record in the database. So two records has two headers.
How can I simply catch the index of the snapshot and only complete the createHeaders function once, or is there a more efficient way of doing this. Below is the JS I am using:
itemsRef.on('value', function(snapshot) {
snapshot.forEach(function(child) {
createHeaders(child.val());
showItems(child.val(), child.key);
});
});
function createHeaders(data) {
var html = '';
html += '<tr>';
$.each(data, function(key, value) {
html += '<th>' + key + '</th>';
});
html += '<th class="text-right">';
html += '</tr>';
$("#tableHeaders").append(html);
}
function showItems(data, key) {
var html = '';
html += '<tr>';
$.each(data, function(key, value) {
html += '<td>' + value + '</td>';
});
html += '<td class="text-right"><a href="/" class="btn btn-primary btn-sm"><i class="fa fa-pencil"></i> Edit</a> <a href="/" class="btn btn-danger btn-sm"><i class="fa fa-times"></i> Delete</a></td>';
html += '</tr>';
$('#results').append(html);
}