JuniorStack2
JuniorStack2

Reputation: 113

No data available in datatable when sort or searching

I have a datatable which is being populated after an ajax call when the page loads. The datatable is populated as expected, but when I click to sort or search, it shows a No data available message and all data previously populated is gone.

I tried to populate it by creating the columns via jquery and via html and search/sort is not working both ways.

$(document).ready(function() {
    $.ajax({
        url: "${pageContext.request.contextPath}/api/list",
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        async: false,
        error: function(response, textStatus) {
            if (response.status == "401") {
                location.href = "${pageContext.request.contextPath}/pages/login.jsp";
            } else {
                alert("error");
            }
        },
        success: function(response, textStatus) {
            populateTable(response)
        }
    });
    function populateTable(response) {
        $(function() {
            $("#dataTable tbody").html("");
            $.each(response, function(i, item) {
                var body = "<tr>";
                body+= "<td>" + item.name + "</td>";
                body+= "<td>" + item.surname + "</td>";
                body+= "</tr>";
                $( "#dataTable tbody" ).append(body);
            });
        });
        $( "#dataTable" ).DataTable();
        
    }
            
});
<div class="card-body">
    <div class="table-responsive">
        <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Surname</th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
    </div>
</div>

I expect to be able to sort and search without getting the No data available message

Upvotes: 0

Views: 1004

Answers (2)

JuniorStack2
JuniorStack2

Reputation: 113

I have used the following example as basis and it is working fine now

http://jsfidsdle.net/gh/get/jquery/2.2/chennighan/RapidlyPrototypeJavaScript/tree/master/lesson4/

Upvotes: 0

MyTwoCents
MyTwoCents

Reputation: 7624

Sorting is not working because may be you are adding rows manually.

By doing so you are not utilizing all features provided by Datatable.

Please try something like this, its more cleaner

$(document).ready(function() {
    $('#dataTable').DataTable( {
        "processing": true,
        "serverSide": true,
        "ajax": {
            "url": "${pageContext.request.contextPath}/api/list"
            "type": "POST",
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
        },
        "columns": [
            { "data": "name " },
            { "data": "surname" }
        ]
    });
});

Upvotes: 1

Related Questions