DataTables ajax.reload() with parameters
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!
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.
$('#example').dataTable({
"ajax": {
"url": "data.json",
"data": function (d) {
d.extra_search = $('#extra').val();
}
}
});
then simply call:
table.ajax.reload();