Ibrahim Khan Ibrahim Khan - 6 months ago 185
Javascript Question

Unable to get data from firebase to my html page

Basically I want to display data from my firebase account to my html div element but I'm unable to do so as the div remains blank.
I'm a beginner to firebase and javascript so please bear with me.
here is the code I've written.

<div class="content">
<h1>Dashboard</h1>
<p>Just DO it!</p>
<div id="box">
<div class="box-top">Bookings</div>
<div class="box-panel">
<script>

var ref = new Firebase("https://fiery-torch-164.firebaseio.com");
ref.on('value', function(snapshot) {
console.log(snapshot.key());
document.write(snapshot.key());
});

</script>
</div>
</div>
</div>


Here is the screenshot of my firebase.

Answer

Currently you are printing the key for the root node which is null. You can print the key for a child node such as the /days.

var ref = new Firebase("https://fiery-torch-164.firebaseio.com/days");
ref.on('value', function(snapshot) {
    console.log(snapshot.key());
    document.write(snapshot.key());
});

For the sake of demo, you could iterate the object properties using javascript's for in loop.

ref.on('value', function(snapshot) {
  console.log(snapshot.key());
  var data = snapshot.val();
  for (var key in data) {
    if (data.hasOwnProperty(key)) {
      document.write(data[key].name + "<br>");
    };
  }
});

JSFiddle: https://jsfiddle.net/bhn139ep/

Access child nodes using nested loops. See JSFiddle for update.

https://jsfiddle.net/bhn139ep/3/

var ref = new Firebase("https://fiery-torch-164.firebaseio.com/days");
ref.on('value', function(snapshot) {

var data = snapshot.val();

//Show Days of week.
for (var key in data) {
    if (data.hasOwnProperty(key)) {
        document.write(data[key].name + "<br>");
    };
}
document.write('<br><br>');

//Show Slots for each day of week using a nested for in loop.
for (var key in data) {
    if (data.hasOwnProperty(key)) {
        var slots = data[key].slots;
        var dayOfWeek = data[key].name;

        for (var slotKey in slots) {
            if (slots.hasOwnProperty(slotKey)) {

                //Get an individual slot.
                var slot = slots[slotKey];

                console.log(slot);
                document.write('Day of week: ' + dayOfWeek + '<br>');
                document.write('Slot Time: ' + slot.time + '<br>');
                document.write('Booked: ' + slot.booked + '<br>');
                document.write('<hr>');
            }
        }                              
    }
}

//Access data within a node directly.
console.log(data['monday'].name); //Prints Monday.
console.log(data['tuesday']['slots']['72'].booked); //prints false.

});
Comments