Fetching data for data tables using ajax method

DataTables can take the data that it is to display from a number of different sources like DOM, JavaScript array, Ajax source, Server-side processing.

DOM:

DataTables a reference to a table which already exists in your HTML page.DataTables will read all of the information about the table from the page (the DOM) and add features such as filtering, paging and sorting.

For example we declare the table head and body in HTML page.

JavaScript:

Data is computed by javascript or when adding a table to a page dynamically.

For example we declare the table body content as array in javascript.

Server-side processing:

Dealing with large data sets (for example 20 million rows) the web-browser simply can’t cope with the amount of processing that is required for DataTables.The server-side process will do all of the pagination, sorting, filtering etc, while DataTables will simply display the results and handle user interaction

Ajax source:

Data can be get from server and displayed in dataTable. A common use case for this is when you are displaying live information which could be periodically updated.

Benefits of using DataTables

1.We can load the table data through json which makes the HTML page render faster.

2. It can support client side and server side searching, sorting and pagination through AJAX/HTML request.

3.It create a DOM element only when required so we can not load all data and render page as very fast.

4.We can handle millions of data in table using server-side processing.

5. we can handle every row data and can be conditionally restrict the table reDraw functions easily.

In this example i am using AJAX source for displaying a DataTable.

Step 1 (HTML file):

Declare the following Data Table structure.

In this line ui-jq=“datatable” which tells AngularJs that this is the data table and ‘ui-options’ tells AngularJs to use the setting from scope variable names ‘ajaxOptions’.

<table id=“ajaxExample” class=“display” width=“100%” ui-jq=“datatable” ui-options=“ajaxOptions”>
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Position</th>
<th>Office</th>
</tr>
</thead>
</table>

Step 2(Controller):

Define scope variable named “ajaxOptions” which will be used as setting for the data tables.

Inside scope variable define the AJAX  method.Please note here “url” is request ajax url and “headers” is request header and then “dataSrc”  is success response source array of objects .

we cannot need to specify “ Request type” as GET.

I have Sample GET request API    “http://datatable.getsandbox.com/datatable”

In this API we get the following sample success response

Success JSON Data :

{
  “users”: [
    {
      “name”: “Airi Satou”,
      “age”: 20,
      “position”: “Chief Executive Officer (CEO)”,
      “office”: “Tokyo”
    },
   {
      “name”: “Rhona Davidson”,
      “age”: 29,
      “position”: “Chief Operating Officer (COO)”,
      “office”: “Tokyo”
     }
   ],
     “total_persons”: 13
}

Here “Users” is a array of object for dataSrc and “total_persons” is another key and values.

AJAX declaration for AngularJs controller:

$scope.ajaxOptions = {
“ajax”: {
    “url”: “http://datatable.getsandbox.com/datatable”,
            “dataSrc”: “users”,
            “headers”: “Content-Type: application/json”
},
“columns”: [
   { “data”: “name” },
           { “data”: “age” },
           { “data”: “position”},
           { “data”: “ office”}
],
   };

When we use dataSrc in ajax options we cannot get other objects and key from dataSrc.

In this example we cannot get “total_persons” from table.

In DataTable AJAX we can use many call back function.

Using Callback method for DataTable AJAX:

fnPreDrawCallback :

Called at the very start of each table draw and can be used to cancel the draw by returning false, any other return (including undefined) results in the full draw occurring.

In this callback ajax call will work and get dat from success response but we can decide the DataTable are draw or not.

In this example i am using checkbox for deciding dataTable are drawn or not.

If checkbox are checked the ajax request called but dataTable not filled otherwise dataTable draw normally.

Example:

“fnPreDrawCallback”: function (oSettings, json){
if ($scope.select.data) {
    return false;
}
}

In this example  “$scope.select.data” is a checkbox value if the value is true it’s return false and cancel the draw otherwise its return always true value.

fnInitComplete:

Called when the table has been initialised. Normally DataTables will initialise sequentially and there will be no need for this function, however, this does not hold true when using external language information since that is obtained using an async XHR call.

This callback can be called after DataTable has been fully initialised. We can get other objects like

outside of “dataSrc” object.

Example:

“fnInitComplete”: function (oSettings, json) {
$scope.$apply(function() {
    $scope.total = json.total_persons;
});
}

In this example init function called after dataTable was drawn and get all JSON data from success response as key name “json”.

I will get a total_persons object value that is outside of “users” object and assign values to $scope.total.

fnDrawCallback:

This function is called on every ‘draw’ event, and allows you to dynamically modify any aspect you want about the created DOM.

In this example i am using setInterval function for ajax reload

ajax.reload() :

it is often useful to be able to reload the table, showing the latest data. This method provides exactly that ability, making an Ajax request to the already defined URL (use ajax.url() if you need to alter the URL).

Example:

setInterval( function () {
$(‘#ajaxExample’).DataTable().ajax.reload();
}, 30000 );

In this example AJAX method called every 30 sec and get a latest success response data.

The latest data (dataSrc object) can be redraw automatically because of reload function but outside of dataSrc object values cannot be get. So using this DrawCallback function we get all AJAX reload function data and we initialise it.

Example:

“fnDrawCallback”: function (oSettings, json){
alert(“DataTables has redrawn the table”);
$scope.$apply(function() {
    $scope.total = json.total_persons;
});
}

In this example we get a latest data form json value and i am reinitialise the latest total_persons value to $scope.total value.

fnRowCallback:

This function allows you to ‘post process’ each row after it have been generated for each table draw, but before it is rendered on screen. This function might be used for setting the row class name etc

Example:

“fnRowCallback”: function( nRow, aData, iDisplayIndex, iDisplayIndexFull) {
var oSettings = $(‘#ajaxExample’).dataTable().fnSettings();
$(“td:first”, nRow).html(oSettings._iDisplayStart+iDisplayIndex +1);
$(nRow).attr(“id”,’row_’ + aData.id);
return nRow;
}

RowCallback function return many values.

Here “nRow” is every dataTable row and “aData” is JSON data of every row and “iDisplayIndex” is index values of every row and “iDisplayIndexFull” is index of the data in the full list of rows.

In this example i set a serial number for every row with pagination using “iDisplayIndex” value and i set a attribute “id” for every row.

Sample project using ajax:

https://github.com/SasiMallow/datatable_ajax

How to use Datatables in AngularJS application

Sasikala,
ROR Junior Developer,
Mallow Technologies.

1 Comment

  1. pratik

    hi

    iam used above code in may project datatable work fine but when use print pdf csv that time first header Sr no is not print event remaining column work fine plz help

Leave a Reply

%d bloggers like this: