TCS
TCS

Reputation: 799

Datatables - Send Parameter dynamically

I created datatable like below;

var costtable = $('#productcategories').DataTable({
    "responsive": true,
    "processing": true,
    "serverSide": true,
    "deferRender": true,
    "ajax": "{{ route('product-json') }}?{!! \Request::getQueryString() !!}",
.....

I need to add/change some parameters with dynamic actions. Like;

$('body').on('change', '.blabla', function(){
var val = $(this).val();
costtable.addparameter('blabla', val);
});

How can I make it possible? I will use that parameter on backend.

Upvotes: 0

Views: 853

Answers (1)

andrewJames
andrewJames

Reputation: 22042

Instead of using the string form of the DataTables ajax option like this...

"ajax": "your_url_here"

...you can use the object form of the syntax:

"ajax": {
  "url": "your_url_here",
  "data": extraRequestParams
}

Based on the question, the object you need to construct will be:

extraRequestParams = { user_id: "some_value" }

...where the value is what you populate from your var val = $(this).val();.

This data will be added to the request data which DataTables automatically generates to support server-side processing:

draw=1&...&start=0&length=25&user_id=some_value

In order for your onchange event to trigger the ajax call, you will need to refer to the DataTable - so, something like this:

var extraRequestParams = {};

$('body').on('change', '.blabla', function(){
  var val = $(this).val();
  extraRequestParams = { user_id: val };
  costtable.ajax.reload();
});

This assumes costtable is defined as your DataTable:

var costtable = $('#example').DataTable( { ... } );

See ajax.reload() for reference.

Upvotes: 1

Related Questions