47

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();
gegobyte
  • 4,945
  • 10
  • 46
  • 76
  • 1
    what does `database.ref().child('leads').once('value').then(function(lead) { console.log(lead.val().email, lead.val().mobile, lead.val().name); });` produce in the console? – Deryck Jul 23 '16 at 15:39
  • 3
    @Deryck it produces 'undefined'. – gegobyte Jul 23 '16 at 16:32

4 Answers4

67

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.

gegobyte
  • 4,945
  • 10
  • 46
  • 76
  • Very useful. Thank you. – Gaetano Piazzolla Sep 04 '17 at 14:18
  • 2
    I really wish this was in the standard docs. Buried deep indeed! – brandonscript Jan 02 '18 at 00:55
  • *firebaser here* there is a section [listen for value events](https://firebase.google.com/docs/database/web/lists-of-data#listen_for_value_events) with an example of this in the documentation guides too. I'd love to know what search terms folks use when they end up here, so we can use those in the documentation too. – Frank van Puffelen May 03 '18 at 16:48
  • @FrankvanPuffelen "I'd love to know what search terms folks use when they end up here" : firebase retrieve data javascript – Helmut Granda Jul 03 '18 at 17:56
6

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"

Jortega
  • 3,616
  • 1
  • 18
  • 21
1
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.

vikscool
  • 1,293
  • 1
  • 10
  • 24
  • When i get the value of the field trough the property (e.g userSnapshot.val().location) it is returning me UNDEFINED value, do you know why? I checked already if my property have the correct name and it does, =( thanks – Fernando Torres May 04 '21 at 00:05
-1

If you want to retrieve data from a post key or client key better to have a separate username like:-

("leads/"+ mobile + "name")
("leads/"+ mobile + "email")
lejlun
  • 4,140
  • 2
  • 15
  • 31