I am using DataTables 1.10
Does anyone know how to dynamically add a parameter to the ajax call before table.draw() so my request has new parameters? I've looked everywhere and cannot find an answer.
I have buttons that a person can press and based on that button send different parameters to the server.
$('#mytable').DataTable({
iDisplayLength: 10,
responsive: true,
processing: true,
serverSide: true,
searching: false,
bLengthChange: false,
bProcessing: true,
paging: true,
ajax: {
url: me.url,
dataType: 'json',
cache:false,
type: 'GET',
data: function ( d ) {
$.extend( d, me.data);
d.supersearch = $('.my-filter').val();
}
},
columns: me.columns,
columnDefs: me.renderer,
initComplete: function() {
}
});
This all works fine but then I try to tie it to a button to pass new parameters.
$('.button').on('click', function(){
var table = $('#mytable').DataTable();
table.ajax.params({name: 'test'}); <- I want to do something like this
table.draw();
})
My way is not so pretty, but very simple and works great: when I want to pass custom parameters while redrawing the DataTable, first I simply change its URL:
$('#table_id').DataTable().ajax.url('/custom/path/with/custom/parameters/inside/');
$('#table_id').DataTable().draw();
Then, if necessary, as a first step of the "on draw.dt" event I change it back to the normal URL:
$('#table_id').on('draw.dt', function() {
$('#table_id').DataTable().ajax.url('/normal/path/for/ajax/source/');
// ...
)};
The only disadvantage of this approach that it needs some trick to squeeze those custom parameters into the alternative path. Besides, it needs some server-side work also to prepare that alternative route and to extract those custom parameters from it.
I have modified your code to do what you need.
Initialize a data table:
$('#mytable').DataTable({
iDisplayLength: 10,
responsive: true,
processing: true,
serverSide: true,
searching: false,
bLengthChange: false,
bProcessing: true,
paging: true,
ajax: {
url: me.url,
dataType: 'json',
cache:false,
type: 'GET',
data: function ( d ) {
$.extend(d, me.data);
d.supersearch = $('.my-filter').val();
// Retrieve dynamic parameters
var dt_params = $('#mytable').data('dt_params');
// Add dynamic parameters to the data object sent to the server
if(dt_params){ $.extend(d, dt_params); }
}
},
columns: me.columns,
columnDefs: me.renderer,
initComplete: function() {
}
});
Handle click event on a button:
NOTE: I'm assuming that this is the only place where you would be adding dynamic parameters for AJAX call.
$('.button').on('click', function(){
// Set dynamic parameters for the data table
$('#mytable').data('dt_params', { name: 'test' });
// Redraw data table, causes data to be reloaded
$('#mytable').DataTable().draw();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With