Update DataTable when doing fetch call

Update DataTable when doing fetch call

SharlotteSharlotte Posts: 1Questions: 1Answers: 0
edited May 2022 in Free community support

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 ?

Answers

  • kthorngrenkthorngren Posts: 21,330Questions: 26Answers: 4,951

    You will probably want to move the $(document).ready(..), lines 54-60, function outside cb function so it executes only once. This way Datatables will initialize against your empty table.

    Then you can replace lines 43-53 with Datatables API's to populate the table. You can do something like this instead:

    var table = $('#all_users').DataTable();
    table.clear();
    table.rows.add( users ).draw();
    

    This uses clear() and rows.add() to populate the Datatable.

    For this to work you will also need to configure columns.data, something like this:

                        $(document).ready(function() {
                            $('#all_users').dataTable({
                                "paging": true,
                                columns: [
                                    { data: 'name' },
                                    { data: 'email' },
                                    { data: 'country' },
                                    { data: 'city' },
                                    { data: 'visit' },
                                    { data: 'temps_moyenne' },
                                ],
                            });
                            $('.dataTables_length').addClass('bs-select');
     
                        });
    

    Kevin

Sign In or Register to comment.