How to retrieve data from firebase with javascript

First open the api

<script src="https://www.gstatic.com/firebasejs/4.10.1/firebase.js"></script>

Then use your credentials to initialize the database

<script>
  var config = {
    apiKey: "********************************",
    authDomain: "**************.firebaseapp.com",
    databaseURL: "https://******************.firebaseio.com/",
    projectId: "******************",
    storageBucket: "https://******************.firebaseio.com",
    messagingSenderId: "**************"
  };
  firebase.initializeApp(config);
  var database = firebase.database()
</script>

Now you are ready to retrieve the data

var dbmusto = firebase.database().ref().child(“4AE”).child(“musto”);

in this variable there will be the link to the recod you want into your database, child must of child 4AE.

Read the value in the record and show it.

In the html code put this

<div id="showdata"></div>

In the script js code this

dbmusto.on("value", snap => showdata.innerText = snap.val());

The value (snap) into the record is put into showdata div with innerText

If you want to change the value in the record on the fly, link it to a variable that you can modify clicking a button, for example

dbmusto.on("value", snap => n_musto = snap.val())

When n_musto changes, the value in the record is changet, becomes the snap.val, to say so. For example, you can change the value of n_musto clicking a button like this:

<button type="button" class="btn btn-info btn-lg" onclick="let n_rucco=0;dbmusto.set(--n_musto)">[ - ]</button>

When we click on the butto the value in the reference dbmusto is set to decrease of 1. It will show in the showdata div, seen right now.

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.