Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ajax to load a jQuery DataTable

I'm trying (and failing) to load a jQuery DataTable using the built-in ajax source argument. The datatable, however, shows the message "Loading..." where the row(s) should be appearing.

Here's my datatable call :

    $('#my-table').dataTable( 
             {bFilter: false,
              bInfo: false,
              bJQueryUI: true,
              bPaginate: false,
              bStateSave: false,
              bSort: false,
              aoColumns: [ {"sTitle" : "Date"}, 
                           {"sTitle" : "Our Co."}, 
                           {"sTitle" : "Their Co."}, 
                           {"sTitle" : "Note"} ], 
              sAjaxSource: "/contact/company_name/"} );

Using Chrome, I can see that the call to /contact/company_name/ is occurring, is returning status 200, and has the following data: [[[Hello], [Goodbye], [Test1], [Test2]]] (which is my test data).

I can also see that the dataTables.min.js is returning the error Uncaught TypeError: Cannot read property 'length' of undefined.

I assume that my returned data is not formatted properly. Can anyone suggest the solution?

like image 322
Larry Lustig Avatar asked Oct 02 '11 21:10

Larry Lustig


2 Answers

according to the website your service should return data in this format:

{
  "aaData": [
    [
      "row 1 col 1 data",
      "row 1 col 2 data",
      "row 1 col 3 data",
      "row 1 col 4 data"
    ],
    [
      "row 2 col 1 data",
      "row 2 col 2 data",
      "row 2 col 3 data",
      "row 2 col 4 data"
    ],
    [
      "row 3 col 1 data",
      "row 3 col 2 data",
      "row 3 col 3 data",
      "row 3 col 4 data"
    ],
    [
      "row 4 col 1 data",
      "row 4 col 2 data",
      "row 4 col 3 data",
      "row 4 col 4 data"
    ]
  ]
}

so, wrap your array in an object, name the array as aaData and try again. or you can name it any way you like, but then you need to add the sAjaxDataProp parameter in the datatables initialisation (say you name it data you would do it like this:

$('#example').dataTable( {
    "bProcessing": true,
    "sAjaxSource": "/ajaxsource/callmydata",
    "sAjaxDataProp": "data"
} );
like image 139
Sander Avatar answered Oct 09 '22 03:10

Sander


If your ajax source returns

[[[Hello], [Goodbye], [Test1], [Test2]]]

This is not ok for datatables. It should be:

{
     iTotalRecords: "54",
     iTotalDisplayRecords: "22",
     aaData: "[['Hello', 'Goodbye', 'Test1', 'Test2']]"
}

aaData stands for array of arrays.

like image 29
Nicola Peluchetti Avatar answered Oct 09 '22 02:10

Nicola Peluchetti