Reputation: 4333
I'm developing a simple User Registration web application which takes name
and email
as an input from the user. Used Firebase as an online data store.
JavaScript file: ( Used JQuery)
databaseRef.orderByKey()
.once('child_added', function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var childKey = childSnapshot.key;
var childData = childSnapshot.val();
console.log("Key: " + childKey + "; Value: " + childData);
$('#nameValue').text(childData);
$('#emailValue').text(childData);
});
});
HTML Code:
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td id='nameValue'></td>
<td id='emailValue'></td>
</tr>
</tbody>
</table>
</div>
</div>
This is my Database structure on Firebase.
users
|
-KhyubUqLRGUGW-rtija
|--- email: "[email protected]"
|--- name: "p1"
I'm able to get these values on Browser Console.
Key: email; Value: [email protected]
Key: name; Value: p1
But I'm unable to display them on my the HTML page. What can be done to my JQuery function in order to display the contents on my HTML page.
This is the current output that I'm getting when I submit the details.
Upvotes: 0
Views: 2628
Reputation: 890
Instead of hardcoding fixed values in your your table's <th>
, you could specify the keys
that are in your database. You could even do the same with the table's data. i.e., values
to those respective keys
.
Modify your HTML code to this:
<div class="table-responsive">
<table class="table">
<thead>
<tr id="keysRow"></tr>
</thead>
<tbody>
<tr id="valuesRow"></tr>
</tbody>
</table>
</div>
This is how you get the data from your Firebase.
databaseRef
.once('child_added', function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var childKey = childSnapshot.key;
var childData = childSnapshot.val();
console.log(childKey + " - " + childData); // Displays key with its value in your Browser Console
$('#keysRow').append('<th>' + childKey + '</th>');
$('#valuesRow').append('<td>' + childData + '</td>');
});
});
Upvotes: 1
Reputation: 3464
Firstly use
$('#nameValue').append(childKey);
$('#emailValue').append(childData);
instead of
$('#nameValue').text(childKey);
$('#emailValue').text(childData);
as .text()
replaces the text every time you call it i.e. it overrides the previous data, what you require is appending the data to previous data.
Secondly you are making a mistake in appending data to table. what you should do is:
$("#data").append('<tr><td>' + childKey + '</td><td>'+ childData+'</td></tr>');
in you updated HTML code:
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody id="data"> <!-- changed -->
</tbody>
</table>
</div>
</div>
Notice that I have removed your .. lines because after appending it would result in incorrect HTML table structure. This is the structure you want W3school example Now it will append properly to your table columns
Upvotes: 2