Search code examples
jquerydatatables

DataTables: .ajax is not defined?


I am using DataTables to display some JSON data successfully. I want to reload the data source with some slightly different JSON, but I am getting errors.

I am calling in DataTables with this line:

<script type="text/javascript" src="https://cdn.datatables.net/v/bs4/jqc-1.12.4/dt-1.10.18/datatables.min.js"></script>

And I am initializing DataTables with this JS code:

$(function(){
    var apiUrl = '/api/people.php';
    var table = dt('#peopleTable').dataTable({
        ajax: {
            dataType: 'text',
            type: 'POST',
            url: apiUrl,
            dataSrc: function (json) {
                return $.parseJSON(json);
            }
        },
        columns: [...] // column definitions here
    });

All of this so far works fine, no problems. The problems are to follow...

So I have this click handler:

    $('.people-type').on('click', function(){
        var id = $(this).data('id');
        table.ajax.url(apiUrl + '?type=' + id).load();
        table.draw();
    });

When this click handler is run, I am told that table.ajax is not defined. Indeed console.log(table); reveals the same thing, although it does seem that table is bound to something that looks like a DataTables object:

console.log output of table

The documentation tells me that my code is correct: https://datatables.net/reference/api/ajax.url().load()#Example

But obviously my DataTables doesn't have the ajax method. Can anyone explain what is going on here?


Solution

  • I think your problem is dataTable() vs. DataTable(). Check this. In your javascript replace the line var table = dt('#peopleTable').dataTable with var table = dt('#peopleTable').DataTable and check if ajax is working