How to retrieve data from Firebase Database?

I'm trying to create a simple program that takes name, mobile number and email address from user and then puts the data on Firebase Realtime Database.

There are 3 input boxes and a button which on click does the above operation. Here is the code:

<input type="text" id="name">
<input type="text" id="mobile">
<input type="text" id="email">

<button type="button" id="button" onclick="addLead()">Submit</button>

I've set up Firebase like this:

<script src="https://www.gstatic.com/firebasejs/3.2.0/firebase.js"></script>
<script>
  // Initialize Firebase
  var config = {
    ...
  };
  firebase.initializeApp(config);

  var database = firebase.database();
</script>

And here is my addLead() function:

function addLead() {
    var clientName = document.getElementById('name').value;
    var clientMobile = document.getElementById('mobile').value;
    var clientEmail = document.getElementById('email').value;

    var newClientKey = database.ref().child('leads').push().key;
    database.ref('leads/'+newClientKey+'/name').set(clientName);
    database.ref('leads/'+newClientKey+'/mobile').set(clientMobile);
    database.ref('leads/'+newClientKey+'/email').set(clientEmail);
}

This is how I put data to database which works.

enter image description here

So the newClientKey is generating some string, it works well when inserting but now how to retrieve? The official documentation is of no help. This generated string might be based on timestamp, if that's the case then generating it again would be impossible.

When retrieving how will I get access to email, mobile and name under that uniquely generated string which was only available at the time of inserting?

Going by the above structure, I need to get 2 levels down to access the required data and because of the lack of documentation, I don't know how to do that, I'm not sure if something like this will work:

database.child().child();

Solution 1:

The answer to this question is buried deep within Firebase Database Reference. forEach() is used to get to the child without knowing the child's exact path.

var leadsRef = database.ref('leads');
leadsRef.on('value', function(snapshot) {
    snapshot.forEach(function(childSnapshot) {
      var childData = childSnapshot.val();
    });
});

Now childSnapshot will contain the required data, the same thing can also be accessed using child_added.

leadsRef.on('child_added', function(snapshot) {
      //Do something with the data
});

The only difference is that in case of forEach(), it will loop through from the start so if any new data will be added, it will also load the previous data but in case of child_added, the listener is only on new child and not the previous existing childs.

Solution 2:

You could also use dot notation to get the value of the child you are looking for for.

Below I just commented out the forEach loop from the highest rated answer and added a console.log().

 var leadsRef = database.ref('leads');
  leadsRef.on('value', function(snapshot) {
      // snapshot.forEach(function(childSnapshot) {
        var childData = snapshot.node_.children_.root_.value.value_;
        console.log("snapshot.node_.children_.root_.value.value_: ", snapshot.node_.children_.root_.value.value_)
      // });
  });

At the time of posting this I am using firebase 5.9.1

src="https://www.gstatic.com/firebasejs/5.9.1/firebase.js"

Solution 3:

var reference = db.ref('/test/');
reference.on('value', function(snapshot) {
snapshot.forEach(function(userSnapshot){
console.log(userSnapshot.val().url)
document.getElementById('gmap').href = userSnapshot.val().location;
document.getElementById('gimg2').src = userSnapshot.val().url;
document.getElementById('name').innerHTML = userSnapshot.val().uid;

I was facing the same issue. I wanted to read the data from the firebase realtime database and print the same on the web. The data I am reading is in the test document. Use the on() function to take the snapshot of it. Firebase provides you with a foreach loop to iterate over the data in the test document. The variable userSnapshot reads the value while looping. The variables location, url, uid are the keys in the test document.

document.getElementById('gmap').href
document.getElementById('gimg2').src 
document.getElementById('name').innerHTML

are the DOM element to print the data on the web

<a id="gmap" class="btn btn-success btn-sm float-right" type="button" 
 role="button">See location </a>
 <p id="name"></p>
 <img id="gimg2" class="img-fluid"/>

I hope this helps someone.