Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataTables add column dynamically to table

I'm using DataTables (datatables.net) to display data from an Ajax source and having trouble customizing it. One thing I would like to do is add a column so I can have for example an 'edit' button for each row.

The closest thing to that in the examples is here but I can't get that to work with an ajax source.

Currently, I'm using the following code to display my table:

fnServerObjectToArray = function ( aElements ){
    return function ( sSource, aoData, fnCallback ) {
        $.ajax( {
            "dataType": 'json', 
            "type": "POST", 
            "url": sSource, 
            "data": aoData, 
            "success": function (json) {
                var a = [];
                for ( var i=0, iLen=json.aaData.length ; i<iLen ; i++ ) {
                    var inner = [];
                    for ( var j=0, jLen=aElements.length ; j<jLen ; j++ ) {

                        inner.push( json.aaData[i][aElements[j]] );
                    }
                    a.push( inner );
                }
                json.aaData = a;
                fnCallback(json);
            }
        } );
    }
}

$(document).ready(function() {
    $('#example').dataTable( {
        "bProcessing": true,
        "sAjaxSource": 'get_data.php',
        "fnServerData": fnServerObjectToArray( [ 'username', 'email' ] )
    } );
}); 
like image 855
Chad Avatar asked Jun 01 '11 07:06

Chad


2 Answers

Why don't you use fnRenderFunction in the aoColumns? As an example:

aoColumns: [ { "bVisible": false} , null, null, null, null,
  { "sName": "ID",
    "bSearchable": false,
    "bSortable": false,
    "fnRender": function (oObj) {
       return "<a href='EditData.php?id=" + oObj.aData[0] + "'>Edit</a>";
     }
  }
]

You can use it to format the value from the server side.

See similar example on the http://jquery-datatables-editable.googlecode.com/svn/trunk/ajax-inlinebuttons.html (ignore specific settings for the editable plugin)

like image 104
Jovan MSFT Avatar answered Oct 04 '22 07:10

Jovan MSFT


I've created columns with edit button and links and so on, but usually i do everything server side by custominzg the data i return and then show/hide them with the aoColumns option. I don't really understand what you are tring to achieve: display server side data as a link?

like image 34
Nicola Peluchetti Avatar answered Oct 04 '22 08:10

Nicola Peluchetti