unable to read data from firebase using html

Viewed 50

I can see data in firebase realtime database from console but If I try to read this data via html/javascript its not giving me anything. I have tried two different ways none worked. I dont think i can attach code here so I will try to put both the code forms below . The format of the data is as follows :

here is revised code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body {text-align: center;}
        #findDetails {float: left; width: 50%; background-color: floralwhite; color: darkslategray;}
        input {width: 120px;}
    </style>
</head>
<body>

    <div id="findDetails">
        <h1>PUMP1</h1>

        <h3 id="Start-time" type="text"></h3>
        <h3 id="Cycle" type="text"></h3>
        <h3 id="Duration-hrs" type="text"></h3>
        <h3 id="Pumped-gals" type="text"></h3> <br><br>
    </div>

<script type="module">
    import { initializeApp } from "https://www.gstatic.com/firebasejs/9.9.4/firebase-app.js";
    import {getDatabase, ref, get, set, child, update, remove} from "https://www.gstatic.com/firebasejs/9.9.4/firebase-database.js"


const firebaseConfig = {
  apiKey: "AIzaSyAKQ4cRyBMBbjhsYpg5w96wVj_-qE4zUGw",
  authDomain: "pump-a559c.firebaseapp.com",
  databaseURL: "https://pump-a559c-default-rtdb.firebaseio.com",
  projectId: "pump-a559c",
  storageBucket: "pump-a559c.appspot.com",
  messagingSenderId: "838180391277",
  appId: "1:838180391277:web:df22c7d634310ae135b264"
};

  // Initialize Firebase
  const app = initializeApp(firebaseConfig);

  // Initialize the database
  const db = getDatabase(app);

  const dbref = ref(db);

    get(child(dbref, "Sensor"))
    .then((snapshot)=>{
        snapshot.forEach((child)=>{
            Start-time.innerHTML = "Start-time: " + child.val().StartTime;
            Cycle.innerHTML = "Cycle: " + child.val().Cycle;
            Duration-hrs.innerHTML = "Duration-hrs: " + child.val().Duration;
            Pumped-gals.innerHTML = "Pumped-gals: " + child.val().GalsPumped;
     //       console.log(child.val().StartTime);
        } else {
            alert("No data found");
        }
    })
    .catch((error)=>{
        alert(error);
       });

    </script>
</body>
</html>

CODE2

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body {text-align: center;}
        #findDetails {float: left; width: 50%; background-color: floralwhite; color: darkslategray;}
        input {width: 120px;}
    </style>
</head>
<body>
  
<ul id="list">

</ul>



<script type="module">
    // Import the functions you need from the SDKs you need
    import { initializeApp } from "https://www.gstatic.com/firebasejs/9.9.4/firebase-app.js";
    import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.9.4/firebase-database.js";
    // TODO: Add SDKs for Firebase products that you want to use
    // https://firebase.google.com/docs/web/setup#available-libraries
  
    // Your web app's Firebase configuration
    // For Firebase JS SDK v7.20.0 and later, measurementId is optional
    const firebaseConfig = {
      apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-qE4zUGw",
      authDomain: "pump-a559c.firebaseapp.com",
      databaseURL: "https://pump-a559c-default-rtdb.firebaseio.com",
      projectId: "pump-a559c",
      storageBucket: "pump-a559c.appspot.com",
      messagingSenderId: "838180391277",
      appId: "1:838180391277:web:df22c7d634310ae135b264",
      measurementId: "G-K66Z05LFCD"
    };
  
    // Initialize Firebase
    const app = initializeApp(firebaseConfig);
        
        var pumpId=0;
        function addItemsToList(starttime,cycle,duration,pumped){
            var ul=document.getElementById('list');
            var header= document.createElement('h2');
            
            var _starttime= document.createElement('li');
            var _cycle= document.createElement('li');
            var _duration= document.createElement('li');
            var _pumped= document.createElement('li');

            _starttime.innerHTML='Start-time: '+starttime;
            _cycle.innerHTML='Cycle: '+cycle;
            _duration.innerHTML='Duration-hrs: '+duration;
            _pumped.innerHTML='Pumped-gals: '+pumped;

            ul.appendChild(header);
            ul.appendChild(_starttime);
            ul.appendChild(_duration);
            ul.appendChild(_pumped);
        }

        function FetchAllData(){
            firebase.database().ref('Sensor').once('value',function(snapshot){
                snapshot.forEach(
                    function(ChildSnapshot){
                        let start = ChildSnapshot.val().StartTime;
                        let cycle = ChildSnapshot.val().Cycle;
                        let duration = ChildSnapshot.val().Duration;
                        let pumped = ChildSnapshot.val().GalsPumped;
                        addItemsToList(start,cycle,duration,pumped);
                    }
                );
            });
        }
        window.onload(FetchAllData());

</script>

</body>
</html>
2 Answers

You're loading the entire Sensor node, which means that you get a snapshot with data for all sensors. To get the data for each specific sensor, you'll need to loop over the child nodes in that snapshot.

So:

get(child(dbref, "Sensor")
.then((snapshot)=>{
    snapshot.forEach((child)=>{
        Start-time.innerHTML = "Start-time: " + child.val().StartTime;
        Cycle.innerHTML = "Cycle: " + child.val().Cycle;
        Duration-hrs.innerHTML = "Duration-hrs: " + child.val().Duration;
        Pumped-gals.innerHTML = "Pumped-gals: " + child.val().GalsPumped;
    } else {
        alert("No data found");
    }
})
.catch((error)=>{
    alert(error);
});

Update: the Start-time and other variables in your code are not defined, and in multiple cases not valid variables names. If you want to access an element from the DOM, you need to get it by calling document.getElementById("Start-time") and then call innerHMTL on its result.

So for example:

get(child(dbref, "Sensor")
.then((snapshot)=>{
    snapshot.forEach((child)=>{
        document.getElementById("Start-time").innerHTML = "Start-time: " + child.val().StartTime;
        ...
    });
});

the following code resolved the issue and now I get my sensor data

            .then((snapshot)=>{
                snapshot.forEach((child)=>{
                    id_PumpID.innerHTML = "Pump ID: " + child.val().PumpID
                    id_StartTime.innerHTML = "StartTime: " + child.val().StartTime;
                    id_Cycle.innerHTML = "Cycle: " + child.val().Cycle;
                    id_Duration.innerHTML = "Duration: " +  child.val().Duration;
                    id_GalsPumped.innerHTML ="GalsPumped: " + child.val().GalsPumped;
                 })
                });```
Related