Home > Enterprise >  Jquery DataTable sorting not working when using ajax to populate data
Jquery DataTable sorting not working when using ajax to populate data

Time:12-21

I have been trying to use ajax to populate data in a table on page load. The data is loaded fine in my table but The issue I am facing is with sorting and pagination of jQuery. as when ever i click its sorting arrow, it shows no data available in the table. My table code is

{{-- /Table Starts form here --}}
                        <table id="DtAdminAttendance" >
                                <thead>
                                    <tr>
                                        {{-- <th style="display: none">tbl_index</th> --}}
                                        <th>Emp ID - Name</th>
                                        <th>Date </th>
                                        <th>Punch In</th>
                                        <th>Punch Out</th>
                                        <th>Worked Hours</th>
                                        <th>Status</th>
                                <th >Action</th>
                                    </tr>
                                </thead>
                                <tbody id="atn-tbody">
                                    {{-- table data goes here --}}
                                </tbody>
                            </table>

my ajax for this table is

<script> //for displaying table data department
$(document).ready(function () {

    
        // var table = $('#DtAdminAttendance').DataTable();
        $.ajax({
            type: "GET",
            url: "fetch-Attendance",
            dataType: "json",
            
            success: function (response) {
                
                $('tbody').html("");
                $.each(response.Attendance_list, function (key, employee) { 
                                if(employee.status=="Absent"){
                                $('tbody').append(
                                            '<tr>\
                                        <td style="display: none">' employee.id '</td>\
                                        <td>'  employee.employeeID   '-'    employee.name   '</td>\
                                        <td>' employee.date '</td>\
                                        <td>' employee.Punch_in '</td>\
                                        <td>' (employee.Punch_Out== null? '-' : employee.Punch_Out ) '</td>\
                                        <td>' employee.totalhours '</td>\
                                            <td >' employee.status '</td>' 
                                            '<td >'
                                             '<div >'
                                                     '<a href="#"  data-toggle="dropdown" aria-expanded="false"><i >more_vert</i></a>' 
                                                '<div >' 
                                                    '<button type="button"  href="#" data-toggle="modal" data-target="#edit_Attendance" value="' employee.id '" ><i ></i> Edit</button>' 
                                                    '<button type="button"  href="#" data-toggle="modal" data-target="#delete_Attendance" value="' employee.id '" ><i ></i> Delete</button>' 
                                                 '</div>'
                                                 '</div>\
                                            </td>\
                                            </tr>'
                                   );
                                        }
                                        else if(employee.status=="Present"){
                                        $('tbody').append(
                                        '<tr>\
                                        <td style="display: none">' employee.id '</td>\
                                        <td>'  employee.employeeID   '-'    employee.name   '</td>\
                                        <td>' employee.date '</td>\
                                        <td>' employee.Punch_in '</td>\
                                        <td>' (employee.Punch_Out== null? '-' : employee.Punch_Out ) '</td>\
                                        <td>' employee.totalhours '</td>\
                                            <td >' employee.status '</td>'
                                             
                                            '<td >'
                                             '<div >'
                                                     '<a href="#"  data-toggle="dropdown" aria-expanded="false"><i >more_vert</i></a>' 
                                                '<div >' 
                                                    '<button type="button"  href="#" data-toggle="modal" data-target="#edit_Attendance" value="' employee.id '" ><i ></i> Edit</button>' 
                                                    '<button type="button"  href="#" data-toggle="modal" data-target="#delete_Attendance" value="' employee.id '" ><i ></i> Delete</button>' 
                                                 '</div>'
                                                 '</div>\
                                            </td>\
                                            </tr>'
                                   );
                                        }
                                        else if(employee.status=="Late"){
                                        $('tbody').append(
                                        '<tr>\
                                        <td style="display: none">' employee.id '</td>\
                                        <td>'  employee.employeeID   '-'    employee.name   '</td>\
                                        <td>' employee.date '</td>\
                                        <td>' employee.Punch_in '</td>\
                                        <td>' (employee.Punch_Out== null? '-' : employee.Punch_Out ) '</td>\
                                        <td>' employee.totalhours '</td>\
                                            <td >' employee.status '</td>'
                                             '<td >'
                                             '<div >'
                                                     '<a href="#"  data-toggle="dropdown" aria-expanded="false"><i >more_vert</i></a>' 
                                                '<div >' 
                                                    '<button type="button"  href="#" data-toggle="modal" data-target="#edit_Attendance" value="' employee.id '" ><i ></i> Edit</button>' 
                                                    '<button type="button"  href="#" data-toggle="modal" data-target="#delete_Attendance" value="' employee.id '" ><i ></i> Delete</button>' 
                                                 '</div>'
                                                 '</div>\
                                            </td>\
                                            </tr>'
                                    
                                        
                                   );
                                        }
                                        else if(employee.status=="Unpaid Halfday"){
                                        $('tbody').append(
                                        '<tr>\
                                        <td style="display: none">' employee.id '</td>\
                                        <td>'  employee.employeeID   '-'    employee.name   '</td>\
                                        <td>' employee.date '</td>\
                                        <td>' employee.Punch_in '</td>\
                                        <td>' (employee.Punch_Out== null? '-' : employee.Punch_Out ) '</td>\
                                        <td>' employee.totalhours '</td>\
                                            <td >' employee.status '</td>'
                                             '<td >'
                                             '<div >'
                                                     '<a href="#"  data-toggle="dropdown" aria-expanded="false"><i >more_vert</i></a>' 
                                                '<div >' 
                                                    '<button type="button"  href="#" data-toggle="modal" data-target="#edit_Attendance" value="' employee.id '" ><i ></i> Edit</button>' 
                                                    '<button type="button"  href="#" data-toggle="modal" data-target="#delete_Attendance" value="' employee.id '" ><i ></i> Delete</button>' 
                                                 '</div>'
                                                 '</div>' 
                                            '</td>' 
                                            '</tr>'
                                   );
                                   }
                });
     $('#DtAdminAttendance').DataTable();
            }
        }); 
});
</script>   

now when i go to the page it loads the table rows normal call

but when i sort using any of the column it shows me no data available in table no data available

CodePudding user response:

After adding the jQuery (script) and dataTable (script, style) references to the HTML file, you should add the following code to the script to sort the dataTable. For the project to work properly, you should add the script you will run to the last file. As far as I've commented, there's no problem applying the dataTable style. You probably didn't add the dataTable script reference to the project. Retest the project using the references in the template below and the commands in the <script> element.

<!DOCTYPE html>
<html lang="en">
    
<head>
    <meta charset="UTF-8">
    <title>Document</title>

    <link rel="stylesheet" href="https://cdn.datatables.net/1.11.3/css/jquery.dataTables.min.css">
    <script src="https://code.jquery.com/jquery-3.5.1.js"></script>
    <script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
</head>

<body>
    <table id="DtAdminAttendance"  style="width:100%">
        <!-- Something -->
    </table>

    <script>
        $(document).ready(function () {
            $('#DtAdminAttendance').DataTable({
                order: [
                    [3, 'desc'],
                    [0, 'asc']
                ]
            });
        });
    </script>
</body>
</html>

CodePudding user response:

Based on my tests, your issue isn't reproducible. It works fine on my side.

JS Fiddle: OP's test code

Nonetheless, your source code could use some improvement and probably this may resolve your issue.

Instead of manually manipulating the HTML table, use the dataTable API to automatically generate the table.

JS Fiddle: Improved source code

HTML

<table id="DtAdminAttendance" >
    <thead>
        <tr>
            <th>tbl_index</th>
            <th>Emp ID - Name</th>
            <th>Date</th>
            <th>Punch In</th>
            <th>Punch Out</th>
            <th>Worked Hours</th>
            <th>Status</th>
            <th >Action</th>
        </tr>
    </thead>
    <tbody id="atn-tbody">
    </tbody>
</table>

JavaScript

Change the ajax: {url: '...'} according to your needs. I.e: '/fetch-Attendance'.

$(document).ready(function () {
    $("#DtAdminAttendance").DataTable({
        scrollX: true,
        autoWidth: false,
        ajax: {
            type: "GET",
            url: "https://run.mocky.io/v3/9ef15223-a192-4f3c-a2fb-843048cb31dc",
            dataType: "JSON",
            dataSrc: "Attendance_list",
            async: true,
        },
        columns: [
            {data: "id"},
            {
                data: "name", "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                    $(nTd).html(`${oData.employeeID   "-"   oData.name}`);
                }
            },
            {data: "date"},
            {data: "Punch_in"},
            {data: "Punch_Out"},
            {data: "totalhours"},
            {
                data: "status", "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                    const statusBtn = $("<span class='badge'></span>");
                    let badgeColor = "badge-secondary";

                    switch (oData.status) {
                        case "Absent":
                            badgeColor = "badge-danger";
                            break;
                        case "Present":
                            badgeColor = "badge-success";
                            break;
                        case "Late":
                            badgeColor = "badge-warning";
                            break;
                        case "Unpaid Halfday":
                            badgeColor = "badge-info";
                            break;

                    }

                    statusBtn.addClass(badgeColor);
                    statusBtn.text(oData.status);

                    $(nTd).html(statusBtn.get(0));
                }
            },
            {
                data: null, "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                    const actionBtn = $(`
                    <div >
                        <div >
                            <a href="#"  data-toggle="dropdown" aria-expanded="false">
                                <i >more_vert</i>
                            </a>
                            <div >
                                <button style="cursor: pointer;" type="button"  data-toggle="modal" data-target="#edit_Attendance" value="${oData.id}">
                                    <i ></i>
                                    Edit
                                </button>
                                <button style="cursor: pointer;" type="button"  data-toggle="modal" data-target="#delete_Attendance" value="${oData.id}">
                                    <i ></i>
                                    Delete
                                </button>
                            </div>
                        </div>
                    </div>
                `);

                    $(nTd).html(actionBtn.get(0));
                },
                orderable: false,
                searchable: false
            }
        ],
        columnDefs: [
            {
                "targets": [0],
                "visible": false
            },
            {
                "defaultContent": "-",
                "targets": "_all"
            }

        ]
    });

});

  • Related