user4285359 user4285359 - 19 days ago 7
HTML Question

Connecting Firebase database values to Firebase Web App

So I have a built a database and a web app both using Google's Firebase. Both the database and the web app have both been deployed and both work. I'm am trying to read value from the database using HTML and javascript. The value that is being displayed on my webpage is null for the two different ways I tried. I have attached a picture of the values saved in the database.

<script src="https://www.gstatic.com/firebasejs/3.6.1/firebase.js">
</script>
<script>
// Initialize Firebase
 
var config = {  
apiKey: "AIzaYUIYUkokngctrIbR9krB6Do",
authDomain: "HelloWorld.firebaseapp.com",
databaseURL: "https://HelloWorld.firebaseio.com/",
storageBucket: "HelloWorld.appspot.com",
messagingSenderId: "8298539696" 
}; 

//This was the first was we tried to do it
firebase.initializeApp(config);
//var rootRef = firebase.database().ref();
//var dist = rootRef.child("dalemccaugh");
var ref = firebase.database().ref();
ref.once("value")
.then(function(snapshot) {
var test = snapshot.child("dalemccaugh").val();

console.log(test);
});

//The was the second way we tried
function printData() {
//console.log(dist)
dist.on("value", function(snapshot) {
console.log(snapshot.val());
}, function(errorObject) {
console.log("The read failed: " +errorObject.code);
});

}
</script>


enter image description here

Answer

"dalemccaugh" is the name of your database. This means it is the root of your JSON hierarchy. If you for example wants to read the "test" object, you can do it like this:

var ref = firebase.database().ref();

ref.child("test").once("value").then(function(snapshot) {
    var test = snapshot.val(); 
    console.log(test);
});

If you want to read the JSON object at the root level, you simply have to remove .child("test") from your reference.