wootscootinboogie
wootscootinboogie

Reputation: 8695

jQuery DataTables Ajax Data Source

I find the documentation for DataTables when using AJAX as the data source limited. I've got a method in my controller in an ASP.NET MVC 4 application that returns a simple JSON result, and I'm trying to fill a DataTable with the following:

$.ajax({
    type: "GET",
    dataType: "json",
    contentType: "application/json",
    url: "/Chart/Ajax",
    success: function (data) {
        var returnData = [];
        for (var i = 0; i < data.length; i++) {
            //makes the data an array of arrays
            returnData.push($.makeArray(data[i]));
        }
        $('#secondary').dataTable({
            "aaData": returnData,
            "aoColumns": [
                { "sTitle": "DrugClass" },
                { "sTitle": "DrugClassSize" },
                { "sTitle": "DistinctPatients" },
            ]
        });
    }
});

Ideally, I wouldn't create the table element until the success callback had fired, but in this instance an empty table element is on the page. With the following code I get the error: Uncaught TypeError: Object [object Object] has no method 'dataTable' the thing is, I already have a different DataTable already on the page and it works fine. This script is at the very bottom of the page, after the working data table. Why am I getting this error and what's an easy way to get DataTables to play nice with AJAX data sources?

Upvotes: 1

Views: 10742

Answers (1)

Declan McNulty
Declan McNulty

Reputation: 3374

It seems as though you are putting the initialisation of the datatable in the success of the ajax call, and what you need to do is set it up the other way round i.e initialise the datatable and set the correct options and the plugin will take care of the rest.

You already have your controller action that returns a json result, so you simply need to set the sAjaxSource to that url, so in your case: "sAjaxSource": "/Chart/Ajax".

You then do what you were going to do in the success of the ajax call and set that function to be the fnServerData option, as shown below:

$('#secondary').dataTable( {
    "bProcessing": true,
    "bServerSide": true,
    "sAjaxSource": "/Chart/Ajax",
    "fnServerData": function ( sSource, aoData, fnCallback ) {

        var returnData = [];
        for (var i = 0; i < aoData.length; i++) {
        //makes the data an array of arrays
        returnData.push($.makeArray(aoData[i]));
       }

        $.getJSON( sSource, returnData , function (json) { 
            /* Do whatever additional processing you want on the callback, then 
           tell DataTables */
            fnCallback(json)
        } );
    }
} );

The fnCallback will then send the json to the datatable in the view.

More information here and here.

Upvotes: 1

Related Questions