How to add rows programmatically to a datatable with a column with generated content like button

How to add rows programmatically to a datatable with a column with generated content like button

kjpradeepkjpradeep Posts: 4Questions: 1Answers: 0

I have my table being created using below lines :

                 t = $('#myTableId').DataTable({
                columns : [ {
                    data : 'col1',
                    'render' : function(data, type, row, meta) {
                        return '<button class="btn btn-danger btn-sm" title="Delete" type="button"                   onclick=\'myfunction('
                                + JSON.stringify(row)
                                + ')\' ><i class="fas fa-trash"></i></button>';
                    }
                }, {
                    data : 'col2'
                }, {
                    data : 'col3'
                }, ]
            });

Then on click of a button on the html page i am invoking the below line :

 t.row.add( [
     {
         "col1" : 1,
     "col2" : "some string",
     "col3": "some other string"
     }
 ] ).draw( false );

Then i am constantly getting the below datatable error :
DataTables warning: table id=myTableId -
Requested unknown parameter 'col2' for row 2, column 1.
For more information about this error, please see http://datatables.net/tn/4

Can someone suggest me why it is unable to recognize the properties from the supplied json. Does it have to be some other way ?

Answers

  • kjpradeepkjpradeep Posts: 4Questions: 1Answers: 0

    i could fix it by first creating a javascript object and then creating a json out of it.

     var myJSON = JSON.stringify(myObj); 
    t.row.add( myObj  ).draw();
    
  • kthorngrenkthorngren Posts: 21,311Questions: 26Answers: 4,948
    edited March 2019

    The problem with this code:

    t.row.add( [
        {
            "col1" : 1,
        "col2" : "some string",
        "col3": "some other string"
        }
    ] ).draw( false );
    

    The row.add() API doesn't expect your row object to be contained in an array since it expects to add only one row. This would work:

    t.row.add( 
        {
            "col1" : 1,
        "col2" : "some string",
        "col3": "some other string"
        }
    ).draw( false );
    

    The row.add() API docs don't state that a JSON string is supported. It may work but its an extra step that you don't need and maybe not supported.

    Kevin

This discussion has been closed.