DataTables.js → How to update your data object for AJAX JSON data retrieval

DataTables!?

I love DataTables.js. It makes working with HTML tables a breeze and increases functionality such as search, sorting and pagination.

Their documentation is stellar, however, it’s still written by devs, so it doesn’t explain code to people like you and me. You know. Normal.

This is why I wanted to write the quick post about how to use dynamic data in your DataTables AJAX request.

The Code

Normally, you would instantiate your DataTable for ajax, like this:

//All code in these examples are written in jQuery
//Notice the code in BOLD
$('#example_table').DataTable({
  'ajax': {
    "type"   : "POST",
    "url"    : '/path/to/your/URL',
    "data"   : {
          "key_example1" : "value_example1",
          "key_example2" : "value_example2"
         },
    "dataSrc": ""
  },
  'columns': [
    {"data" : "metric_name"},
    {"data" : "metric_type"},
    {"data" : "metric_timestamp"},
    {"data" : "metric_duration"}
  ]
});

The Wrong Way

It took me a min to figure out this is how they wanted you to send the data, as their documentation makes it seems like you would write something like:

example_table.ajax.data({//object properties here});

However this way doesn’t work at all and simply throws errors.

The Right Way

Now what’s really nice about DataTables is the ability to use a function for that data property :

var example_table = $('#example_table').DataTable({
  'ajax': {
    "type"   : "POST",
    "url"    : '/path/to/your/URL',
    "data"   : function( d ) {
      d.example_key1= $('#example_input1').val();
      d.example_key2= $('#example_input2').val();
      d.example_key3= $('#example_input3').val();
    },
    "dataSrc": ""
  },
  'columns': [
    {"data" : "metric_name"},
    {"data" : "metric_type"},
    {"data" : "metric_timestamp"},
    {"data" : "metric_duration"}
  ]
});
//To Reload The Ajax
//See DataTables.net for more information about the reload method
example_table.ajax.reload()

As you can see, you simply can see any property of the parameter “d” and set a value. DataTables will then set the “data” object to those properties.

For example, if the values of example_input1, example_input2, or example_input3 change, simply reload the ajax method of DataTables by using :

example_table.ajax.reload()

and your table will perform the ajax call along with the new values provided.

Happy Coding!

FavoriteLoadingAdd to favorites
Spread the love

Author: Shahzad Khan

Software developer / Architect