Update Html Table in realtime as data on Firebase RTDB changes

I have an HTML Table linked to a Firebase Real time database. Everything works fine except for one small issue.By using databse.on() instead of database.once(), the table does update as data is changed in the RTDB but it does not ‘replace’ the previously present fields in the table, it instead creates a new set of the updated values.

First Initialization

This is what it does on data update currently:

On Data Update

Heres the HTML script:

<html>
<head>
<meta charset="utf-8">
<title>Customer table</title>
<script src="https://www.gstatic.com/firebasejs/4.2.0/firebase.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.2.0/firebase.js"></script>

<body>
 <table class="table table-striped" id="ex-table">
  <tr id="tr">
    <th>Name</th>
    <th>Credit</th>
  </tr>
</table>

<script>
  var config = {
     apiKey: "AIzaSyB0WrqbEu4kgR1-INNyKpAu8bfvfy0VOVc",
authDomain: "fir-freelance-fd0e6.firebaseapp.com",
databaseURL: "https://fir-freelance-fd0e6-default-rtdb.firebaseio.com",
projectId: "fir-freelance-fd0e6",
storageBucket: "fir-freelance-fd0e6.appspot.com",
messagingSenderId: "967741636284",
appId: "1:967741636284:web:426d2ef2112f9008945ab9"
  };
  firebase.initializeApp(config);
  var database = firebase.database().ref().child('Members');
  database.on('value', function(snapshot){
      if(snapshot.exists()){  
        var content = '';
         
          snapshot.forEach(function(data){
              var Name = data.val().Name;
              var Credit = data.val().Credit;
              content += '<tr>';
              content += '<td>' + Name + '</td>';//column1
              content += '<td>' + Credit + '</td>';//column2
              content += '</tr>';
 
         });

$('#ex-table').append(content); 

}
});
</script>

Ive tried changing .append with .replaceWith but that dosent work either. What im looking is just for the values that have been updated in RTDB to update in the table like this:

enter image description here

1 thought on “Update Html Table in realtime as data on Firebase RTDB changes”

  1. The simplest way to fix this is to clear the table before adding the updated content:

    $('#ex-table').html(content); 
    

    If you have many updates and/or many nodes, this may cause the HTML to flicker. If that is a problem for your app, you can listen to the child_ events instead of the whole value and perform more granular updates to the HTML based on whether the child node was added, changed, or removed.

    Reply

Leave a Comment