Add parameter to datatable ajax call before draw

I am using DataTables 1.10

Does anyone know how to dynamically add a parameter to an ajax call before table.draw (), so my query has new parameters? I searched everywhere and cannot find the answer.

I have buttons that a person can click and send different parameters to the server on this button.

$('#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 great, but then I try to bind it to a button to pass in new options.

 $('.button').on('click', function(){ var table = $('#mytable').DataTable(); table.ajax.params({name: 'test'}); <- I want to do something like this table.draw(); }) 
+8
jquery datatables
source share
2 answers

I modified your code to do what you need.

Initialize the 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 a click event:

NOTE. I assume this is the only place you add dynamic parameters to call AJAX.

  $('.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(); }); 
+4
source share

My method is not so beautiful, but very simple and works fine: when I want to pass user parameters when redrawing a DataTable, first I just change its URL:

 $('#table_id').DataTable().ajax.url('/custom/path/with/custom/parameters/inside/'); $('#table_id').DataTable().draw(); 

Then, if necessary, as the first step of the "on draw.dt" event, I will return it back to the normal URL:

 $('#table_id').on('draw.dt', function() { $('#table_id').DataTable().ajax.url('/normal/path/for/ajax/source/'); // ... )}; 

The only drawback to this approach is that it needs some sort of trick to compress these tunable parameters into an alternative path. In addition, server-side work is also required to prepare this alternative route and to extract these configurable parameters from it.

+1
source share

All Articles