0
votes

I've been working with datatables and I'm able to load the datatable using getJson with strongly typed classes etc and it works just great. Until I hit one snag.

There are times I want to populate a datatable with data that "I don't know about" but I always know that it will be one row of data - it is simply a json string with dynamic content.

Now with datatables you can simply populate the table with aaData and aaCol by assigning a json string to it but my json string contains a column and data IE:

First_name:bob and so on.

A column - on Datatables would be populated with sTitle:Column1 etc and assigned to aaCol.

Does anyone know of a plug in that parses a json string into aaCol and aaData for use with datatables?

1
Could you give an example of "strongly typed classes" that you use, and an example of a json that doesn`t work? - Rafael Teles
Here's a json string which is valid: "[{"DTAP_EXEMPT":0.015,"DTAP_FULLY_IMMUNIZED":0.985}]" There are two columns. I could create a class with a getter and a setter with those columns - problem is that which each request we don't know what columns we are getting back hence I wan to populate dynamically. - dawriter
Ok, I understand that the columns are not static. But do you know which columns are present before setting the data to DataTables? In your example, you would have to known that value of "DTAP_EXEMPT" is used for the first column (or second), and "DTAP_FULLY_IMMUNIZED" for the other column. I had the same problem and have the solution (if I got the idea right). You can specify for the dataTables to extract the values from the fields of the object - Rafael Teles
That's what I'm struggling with - how did you popluate the aaCols without having to specify them in HTML? What was your solution? Thanks. - dawriter

1 Answers

0
votes

I believe you can solve your problem using this approach:

$(document).ready(function() {
    $('#example').DataTable( {
        "processing": true,
        "serverSide": true,
        "ajax": "scripts/objects.php",
        "columns": [
            { "data": "first_name" },
            { "data": "last_name" },
            { "data": "position" },
            { "data": "office" },
            { "data": "start_date" },
            { "data": "salary" }
        ]
    } );
} );

In the example above the dataTables uses a serverSide processing, the ajax return a object like this:

{
  "draw": 1,
  "recordsTotal": 57,
  "recordsFiltered": 57,
  "data": [
    {
      "first_name": "Airi",
      "last_name": "Satou",
      "position": "Accountant",
      "office": "Tokyo",
      "start_date": "28th Nov 08",
      "salary": "$162,700"
    }, ...

You can also set the column name using the "name" property inside the specification of each column.

You can the full example in the following link. If you need more assistance I can make a code on my own later today =)

You can check this JsFiddle to understand how to set the columns names