Skip to content
Advertisement

Update DataTable when doing fetch call

This is the table i want to apply DataTable on :

<div id="reportrange" style="background: #fff; cursor: pointer; padding: 5px 10px; border: 1px solid #ccc;">
<span></span>
</div>
<table id="all_users">
                        <thead>
                            <tr>
                                <th>User</th>
                                <th>Email</th>
                                <th>Country</th>
                                <th>City</th>
                                <th>Engaged sessions</th>
                                <th>Avg Session Duration</th>

                            </tr>
                        </thead>
                        <tbody id="table_body">
                        </tbody>
                    </table>

In my basic code, i have a dateRangePicker that displays the calendar, and based on the interval of dates chosen, there will be a fetch method to my server to fetch data from the database and display them in the table.

 $('#reportrange').daterangepicker();
        $(function() {

            var start = moment().subtract(10, 'days');
            var end = moment();

            function cb(start, end) {
                $('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
                let data = {
                    start_time: start.format('YYYY-MM-DD'),
                    end_time: end.format('YYYY-MM-DD')
                }
                let data_json = JSON.stringify(data)
                fetch("../backend/peopleExplorer1.php", {
                    method: 'POST',
                    headers: {
                        "Content-Type": "application/json",
                    },
                    body: data_json
                }).then(r => r.json()).then(r => {
                    let numbers_of_users_chart = r['numbers_of_users_chart'];
                    let avg_time_chart = r['avg_time_chart'];
                    let add_date = r['add_date'];

                    //fill the table
                    let name_users = r['name_current_user'];
                    let number_sessions = r['number_of_sessions'];
                    let avgtime = r['avg_time'];
                    let email = r['email'];
                    let country = r['country'];
                    let city = r['city'];
                    let users = [];
                    for (let i = 0; i < name_users.length; i++) {
                        users.push({
                            name: name_users[i],
                            email: email[i],
                            country: country[i],
                            city: city[i],
                            visit: number_sessions[i],
                            temps_moyenne: avgtime[i]
                        });
                    }
                    let tableData = "";

                    users.map((values) => {
                        tableData += ` <tr><td>${values.name}</td>
                                   <td>${values.email}</td>
                                   <td>${values.country}</td>
                                   <td>${values.city}</td>
                                   <td>${values.visit}</td>
                                   <td>${values.temps_moyenne} s</td>
                                </tr>`
                    })
                    $(document).ready(function() {
                        $('#all_users').dataTable({
                            "paging": true,
                        });
                        $('.dataTables_length').addClass('bs-select');

                    });
                    document.getElementById("table_body").innerHTML = tableData;
                })

            }

            $('#reportrange').daterangepicker({
                startDate: start,
                endDate: end,
                ranges: {
                    'Today': [moment(), moment()],
                    'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                    'Last 7 Days': [moment().subtract(6, 'days'), moment()],
                    'Last 30 Days': [moment().subtract(29, 'days'), moment()],
                    'This Month': [moment().startOf('month'), moment().endOf('month')],
                    'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
                }
            }, cb);

            cb(start, end);

The problem that i have is regarding the datatable. When i first load the page, i get the correct data in the DataTable : 1 But when i change the daterange, the data does get refreshed but as a normal table as if the DataTable doesn’t exist(there is no pagination and all the elements are displayed on html with no pagination option). Is there a way to fix it as to whenever i change the date the data updates INSIDE the datatable ?

Advertisement

Answer

You basically need to re-initialize DataTable after you insert new rows (dynamically) to your table.

To achieve this, DataTable lets you destroy() the original table you built, and then initialize it again.

Here is a working snippet based on your code, clicking the “populate” button will trigger the procedure:

const theTableBody = document.getElementById("table_body")

function populate() {
  let tableData = ''
  for (let i = 0; i < 20; i++) {
    tableData += `
      <tr>
      <td>${i}</td>
      <td>${i}</td>
      <td>${i}</td>
      <td>${i}</td>
      <td>${i}</td>
      <td>${i} s</td>
      </tr>`
  }
  theTableBody.innerHTML = tableData
}


var dataTableHandler = $('#all_users').DataTable({
  "paging": true,
})


$('#populateBtn').on('click', function(e) {
  // FIRST, WE DESTROY THE TABLE
  dataTableHandler.destroy()
  
  // SECOND, WE POPULATE THE TABLE WITH NEW ROWS
  populate()
  
  // THIRD, WE RE-INITIALIZE THE TABLE
  dataTableHandler = $('#all_users').DataTable({
    "paging": true,
  })
})
<link href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/js/jquery.dataTables.min.js"></script>



<button id="populateBtn">Dynamically populate the table</button>

<table id="all_users" border="1">
  <thead>
    <tr>
      <th>User</th>
      <th>Email</th>
      <th>Country</th>
      <th>City</th>
      <th>Engaged sessions</th>
      <th>Avg Session Duration</th>
    </tr>
  </thead>
  <tbody id="table_body">
  </tbody>
</table>
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement