Home > Back-end >  how to fetch Json Data to real Time updating Html Table?
how to fetch Json Data to real Time updating Html Table?

Time:01-18

i have a Json data file where data is updating every second. i want to show data in Html page of my website in real time without loading page. i'm beginner in javascript i'm just learning please Help me. thanks in advance.

Here is My Json data file: Here

Here is My Html table Page (Result): Here

i want to show data in real time without loading page like stock price update. please help.

 <!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://code.jquery.com/jquery-3.5.1.js">
    </script>
  
    <!-- CSS FOR STYLING THE PAGE -->
    <style>
        table {
            margin: 0 auto;
            font-size: large;
            border: 1px solid black;
        }
  
        h1 {
            text-align: center;
            color: #006600;
            font-size: xx-large;
            font-family: 'Gill Sans', 
                'Gill Sans MT', ' Calibri', 
                'Trebuchet MS', 'sans-serif';
        }
  
        td {
            background-color: #E4F5D4;
            border: 1px solid black;
        }
  
        th,
        td {
            font-weight: bold;
            border: 1px solid black;
            padding: 10px;
            text-align: center;
        }
  
        td {
            font-weight: lighter;
        }
    </style>
</head>
  
<body>
    <section>
        <h1>My Google Sheet Table</h1>
  
        <!-- TABLE CONSTRUCTION-->
        <table id='mytable'>
            <!-- HEADING FORMATION -->
            <tr>
                <th>Date</th>
                <th>Name</th>
                <th>Phone Number</th>
                <th>Months</th>
            </tr>
  
            <script>
                $(document).ready(function () {
  
                    // FETCHING DATA FROM JSON FILE
                    setInterval(function () {$.getJSON("JsonDataFileLink", 
                            function (data) {
                        var content = '';
  
                        // ITERATING THROUGH OBJECTS
                        $.each(data, function (key, value) {
  
                            //CONSTRUCTION OF ROWS HAVING
                            // DATA FROM JSON OBJECT
                            content  = '<tr>';
                            content  = '<td>'   
                                value.SN   '</td>';
  
                            content  = '<td>'   
                                value.Name   '</td>';
  
                            content  = '<td>'   
                                value.Phone   '</td>';
  
                            content  = '<td>'   
                                value.Months   '</td>';
  
                            content  = '</tr>';
                        });
                          
                        //INSERTING ROWS INTO TABLE 
                        $('#mytable').append(content);
                    });
                    
                    }, 3000);
                });
                
            </script>
    </section>
</body>
  
</html>
 

CodePudding user response:

I added your json file url to fetchData() to download the correct file and then I added a callback to be invoked when the data fetched is ready to be processed.

Data Transform: from array of objects to table rows

The transformation is a chain of map and reduce as follows...

Map (over json array of objects):

Iterates over the objects found in the json array and for each one of them it will return a new <tr> element mapped to the corresponding json object in the array.

Reduce (over the fields expected to be found in the object):

The reduction begins from the cols array telling the name of the properties that will be found in the json objects array in the same order they are wished to be displayed.

It just iterates over them, grabs the current value that gets embedded in a new <td> that gets appended to the new <tr>

Each reduce call will just return a new <tr> object as that.

Once we have the final map:

The final result is rows that just are appended to the table tbody once the processing is over.

Attention!

I see the json returned from that url isn't always the same. The date property is changing and some items at the end are empty sometimes.

Automatic refresh

I spent so much thoughts doing the data fetch algorithm that I was ignoring yours already worked and you just needed the refresh of data every once in a while without actually reloading the page.

So here I used setTimeout that will call after a given delay (pollingDelay default at 3000ms) the fetchData and at each iteration, after the table gets refreshed, it calls again the same setTimeout and updates the last time data was updated.

const pollingDelay = 3000;

function fetchData(refreshTable) {
  url = 'https://script.googleusercontent.com/macros/echo?user_content_key=zASWVI1B2eWR37WJ_8Pn0h5WCuVP_1udOD8ZY6sMSzTfAo55CT4-ovYqEXJO5ZtrHrBeT9cYNecnp-Gzuq8TCmDVQfQQO1qjm5_BxDlH2jW0nuo2oDemN9CCS2h10ox_1xSncGQajx_ryfhECjZEnMs1tm11-lp-Q13okfTSX_i5IzvU5JZnhqqg8H90dlfD5jU3SrNArGaMaXSvzMBh2h5A-lJ1RFia7VipeMnCxQqExfB7Qd_-iQ&lib=MVoeqw6DJ9bzix14T3i_S_jbsQ0CRhLAj';
  $.getJSON(url, function(data) { refreshTable(data) });
}

//callback to be passed at fetchData
const cb = (data)=>{
  
  //json object properties in the order how the are wished to be displayed on table
  const cols = ['SN', 'Name', 'Phone', 'Months'];
  
  var rownum = 0;
  //maps the data items to table rows
  const rows = data.map( entry => {
      //creates a table row using reduce over cols
      const newrow = cols.reduce(
          (row, col) => { return $(row).append( $('<td>').text(entry[col]) ); }, $('<tr>')
      );
      //adds the data attribute data-rownum on the <tr>
      newrow[0].dataset.rownum =   rownum;
      //returns the new row
      return newrow;
  });
  
  //empties table and appends new row
  $('#mytable tbody').empty().append(rows);      
  
  //updates the time at which the table was refreshed
  const now = new Date();  
  $('#refresh').text(`Data refreshed at: ${now.getHours()}:${now.getMinutes()}:${now.getSeconds()}`);  
  
  //set a new timer before calling again the fetchData()
  setTimeout(fetchData(cb), pollingDelay)
}

$(document).ready(function() {  
  setTimeout(fetchData(cb), pollingDelay)
});
#refresh{
  border: solid;
  text-align: center;
  font-size: 3rem;
}

table {
  margin: 0 auto;
  font-size: large;
  border: 1px solid black;
}

h1 {
  text-align: center;
  color: #006600;
  font-size: xx-large;
  font-family: 'Gill Sans', 'Gill Sans MT', ' Calibri', 'Trebuchet MS', 'sans-serif';
}

td {
  background-color: #E4F5D4;
  border: 1px solid black;
}

th,
td {
  font-weight: bold;
  border: 1px solid black;
  padding: 10px;
  text-align: center;
}

td {
  font-weight: lighter;
}

tr:before{
  content: attr(data-rownum);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<body>
  <section>
    <div id="refresh"></div>
  
    <h1>My Google Sheet Table</h1>
    
    <table id='mytable'>
      <thead>
        <th>Date</th>
        <th>Name</th>
        <th>Phone Number</th>
        <th>Months</th>
      </thead>
      <tbody>
        <tr>
          <td colspan="4">Loading... please wait</td>
        </tr>
      </tbody>
    </table>
  </section>
</body>

  • Related