eComEvo
eComEvo

Reputation: 12559

DataTable().ajax.reload() not defined

I have the following code under DT v1.10:

var oTable = $('#items')
    .dataTable({
        sDom: "<'row'<'col-md-4'l><'col-md-6'f>r>t<'row'<'col-md-4'i><'col-md-7'p>>",
        oLanguage: {
            sLengthMenu: "_MENU_ per page"
        },
        ajax: "/items",
        bProcessing: true,
        bServerSide: true,
        aoColumnDefs: [
            {
                aTargets: [-1],
                bSearchable: false,
                bSortable: false
            }
        ]
    })
    .on('click', '.btn-danger', function (e) {
        if (confirm('Are you sure you want to delete SKU "' + $(this).data('sku') + '"?')) {
            $.getJSON($(this).attr('href'), function (data) {
                if ('success' in data) {
                    oTable.ajax.reload(null, false);
                }
            });
        }
        event.stopPropagation();
        return false;
    });

When the server responds with success, it tries to call the line oTable.ajax.reload(null, false); but I always get the error Uncaught TypeError: Cannot read property 'reload' of undefined

What am I doing wrong here?

Upvotes: 7

Views: 20111

Answers (2)

Artur Filipiak
Artur Filipiak

Reputation: 9157

You're using old API: $().dataTable() (v1.9 and earlier) which is still available in DataTables v1.10. The old API returns jQuery object, so you should use .api() in order to use DataTable API methods:

oTable.api().ajax.reload();

The new API is returned via: $().DataTable()

Datatables FAQ

Q.: I get an error message stating that an API method is not available
A.: Very likely you are using a jQuery object rather than a DataTables API instance. The form $().dataTable() will return a jQuery object, while $().DataTable() returns a DataTables API instance. Please see the API documentation for further information.

API documentation

It is important to note the difference between $( selector ).DataTable() and $( selector ).dataTable(). The former returns a DataTables API instance, while the latter returns a jQueryJS object. An api() method is added to the jQuery object so you can easily access the API, but the jQuery object can be useful for manipulating the table node, as you would with any other jQuery instance (such as using addClass(), etc.).

Upvotes: 24

davidkonrad
davidkonrad

Reputation: 85528

As a follow up to phillip100's answer, you dont have to change all your old code, or change the initialization method just to use the new API. You can always get the dataTables 1.10.x API on the fly :

...
if ('success' in data) {
  //oTable.ajax.reload(null, false);
  $('#items').DataTable().ajax.reload(null, false);
}
...

Would be perfectly well too. jQuery dataTables check if there already is a dataTables instance of $("#items"), so there will be no redundancy.

Upvotes: 10

Related Questions