How can datatables use a value in object for a column render function

How can datatables use a value in object for a column render function

leons1982leons1982 Posts: 1Questions: 1Answers: 0
edited February 2017 in Free community support

My problem is when using a AJAX JSON response for columns, I cannot use the render option.

I think the cause is that the value in the JSON is a string (surrounded with double quotes) which cannot be used by datatables for the render option.

Here is the Javascript I am using:

$.ajax( {
    'url': './controller.php?task=get_stats',
    'type' : 'get',
    'success': function ( response ) {
        table = $( '#example' ).DataTable( {
            'data': response.data,
            'columns' : response.columns,
        } );
    }
} );

This is the JSON response containing data and column for datatables to use:

{
    "columns":[
        {
            "title":"ID",
            "data":"id",
            "render": "function ( data, type, row ) { return data; }"
        },
        {
            "title":"Name",
            "data":"name"
        },
        {
            "title":"Visitors",
            "data":"visitors"
        }
    ],
    "data":[
        {
            "id":593,
            "name":"Test Offer Feb 2017",
            "visitors":0
        }
    ]
}

Answers

  • allanallan Posts: 63,852Questions: 1Answers: 10,519 Site admin

    I cannot use the render option.

    You can, but you can't use it as a function. That is because Javascript functions are not valid JSON. That is not a limitation of DataTables, but rather of the JSON format (and is what makes it safe to use!).

    You have two options:

    1. Define the functions on the client-side
    2. Include the rendered data in the JSON and have the columns.render option point at that.

    Allan

This discussion has been closed.