T Neate T Neate - 1 month ago 20
Javascript Question

Firebase Web not working

Hello I am trying to make a web site utilizing Firebass as my back end but I am having trouble reading data from the data base. I've double checked the paths and yes there is data there. If someone could give a quick look at what I am doing wrong I would really appreciate it. I am not getting any errors, its just not working.

<html>
<head>
<script src="https://www.gstatic.com/firebasejs/3.5.2/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.5.2/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.5.2/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.5.2/firebase-database.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
authDomain: "my-app.firebaseapp.com",
databaseURL: "https://my-app.firebaseio.com",
storageBucket: "my-ap.appspot.com",
messagingSenderId: "123456789"
};

</script>
<script>


function main(){
firebase.initializeApp(config);
var database = firebase.database();
var ratesRef = database.ref("users/rates");
ratesRef.on('child_added', function(snapshot){
console.log("Working");
console.log("lat:" + snapshot.val().latitude);
});
}

</script>
</head>
<body onload="main();">
hello
</body>
</html>

Answer

To read from database, you need 2 callbacks, 1 for reading, 1 for errors. This will work for you:

firebase.database().ref("users/rates").once('value', readFn(),errFn(errorObject))

or replace main with this

function main(){
firebase.initializeApp(config);
var database = firebase.database();
var ratesRef = database.ref("users/rates");
ratesRef.on('child_added', function(snapshot){
    console.log("Working");
    console.log("lat:" + snapshot.val().latitude);
}, function(err) {console.log(err)});
}

You should also use once to prevent reading more than once when you request it