Skip to content Skip to sidebar Skip to footer

DataTables Ajax.reload() With Parameters

I am using DataTables serverSide in an Angular2 project. I am trying to reload the table after making changes, and those changes I want to pass them as parameters in POST via AJAX.

Solution 1:

I finally got the solution, the problem was that I was too focused on achieving my goal through DataTable().ajax.reload(). I wanted to pass the parameters through there in one way or another, and that was incorrect.

I had to change the construction of the options object. As you saw earlier, I was assigning my custom parameters to the options object like this:

ajax: {
  url: this.jsonApiService.buildURL('/test_getUsers.php'),
  type: 'POST',
  data: this.params,
}

Where data: this.params would get the data from somewhere, in my case, I had 2 listeners, one for init and another for updating that change this.params value. This, instead of a listener could be an onChange(), but the point is that the parameters change at runtime.

So I simply had to put this into a function, and merge DataTable's parameters to my own parameters.

This is my solution:

data: function (d) {
    Object.assign(d, myClass.params);
    return d;
}

With this options object, when I have to refresh the DataTable sending new parameters to the server, I simply call ajax.reload(). DataTables will get the options object with the latest data and reload itself.

I really hope this can help someone! Good work and happy coding!


Solution 2:

In some cases you may want to change ajax url at runtime or apply any additional query parameters.

So you can do like this:

var dataTable = $('#example').DataTable({...});    
dataTable.ajax.url('/new-ajax-url?someParam=1').load();

It works with version v1.10.16 of the library.


Solution 3:

$('#example').dataTable({
  "ajax": {
    "url": "data.json",
    "data": function (d) {
        d.extra_search = $('#extra').val();
    }
  }
});

then simply call:

table.ajax.reload();

Post a Comment for "DataTables Ajax.reload() With Parameters"