2

I am using a jQuery DataTable on a site, but all the data in the table changes every time I press a different hyperlink. So rather than delete the rows and add them one by one, is there a way to dynamically remove the entire DataTable and recreate another one with all the data with an array.

The code here is just plan old static stuff but I know how to dynamically fetch the array, let's say the array looks like this when I get it back from python/cherryPy: ar[n]=["col1","col2","col3","col4",..."coln"] :

The code below is the static code for creating the DataTable in the HTML (static)...

<div id="div1" class="ctnr">
   <table id="mainTable1" class="dtable" cellpadding="3" cellspacing="1" border="0">
    <thead>
        <tr><th>*</th><th>Proposal</th><th>Vote </th><th> For </th><th>dd</th><th>A</th></tr>
    </thead>
    <tbody id="tbdy"> 
       <tr id="zrow1" class="gradeX"><td><input id="ckb1" type="checkbox" class = "tb" /></td><td id="ppl1" class="ppsal" style="width:55%">BlaBlaBla</td><td>More BlaBlaBla</td><td class="ralign"> CheeCheeChee</td><td class="ralign"> ChooChoo...</td><td class="ralign"> LaLaLa</td></tr>
    </tbody>
  </table>
</div>

How would I do this in JavaScript or jQuery?

Dennis

DKean
  • 2,017
  • 6
  • 19
  • 28
  • what have you tried? looking for just a little input? try jquery's .html() function – Th0rndike Mar 19 '12 at 14:55
  • I have looked at the DataTable forum and everyone seems to make a huge and complex reply for special cases. I just need a generic case. It has to be simple – DKean Mar 19 '12 at 15:08
  • Using json to populate is a pretty common approach. See http://stackoverflow.com/questions/9760661/jquery-code-to-display-json-response-to-a-html-table-using-append/9761282#9761282 – dwerner Mar 19 '12 at 15:21
  • Thanks, I am able to transport the data. That is not my worry. – DKean Mar 19 '12 at 20:05

2 Answers2

6

DataTables lets you define the structure and data of the table programmatically using what they call "data sources".

There are a few examples in the documentation. I'm not sure which one will suit you but here are a few to get you started:

You could combine that with the bDestroy() method to avoid recreating the <table> tag.

A different approach would be to re-set the rows without recreating the table. There is no setData() method that I know of, but you could use the fnClearTable() and fnAddData() methods to achieve the same result. You can read more about these methods in the DataTables API docs.

jmlnik
  • 2,867
  • 2
  • 17
  • 20
  • You are the man Jonathan! Just what I wanted... Thanx. I'm not done, but I see the solution I need in "DataTables dynamic creation example " – DKean Mar 19 '12 at 15:36
  • I have added datatables to an element ` $("#element").dataTable()` now i want to remove the dataTable from this element. how can i do this. ?????? – Sarfraz Ahmad Dec 06 '13 at 12:20
  • @SarfrazAhmad, you should have created a new question... What you're looking for is `fnDestroy()`: http://datatables.net/api – jmlnik Dec 07 '13 at 01:16
  • thank you Dotjon, I have created a new question also, see here [http://stackoverflow.com/questions/20427543/datatables-are-not-updating-in-meteorjs/20435636?noredirect=1#20435636]' – Sarfraz Ahmad Dec 07 '13 at 05:08
1

hello i had the same issue... and this was how i solved it...

i had this function in a laravel controller... that loops and creates a table dynamically.. based on the $app_id variable... and i had to append the datatable to it... at runtime...

public function getAppUserProfile(Request $request){
    $app_id = $request['appId'];
    $configs = Userconfig::with('user')->where('config_id', $app_id)->get();
    $ct = 1;
    $str = '';
    foreach($configs as $config){

           // $config->user->id,
            $str .= '<tr><td>'. $ct.'</td><td>'.
                    $config->user->profile->first_name
                 .'</td><td>'.
                    $config->user->profile->first_name
                .'</td><td>'.
                    $config->user->profile->first_name
                .'</td></tr>';

            $ct++;
    }

    $tb = '<table id="testTable2" class="table table-striped table-bordered"><thead>';
    $tb .= '<tr><th>S/N</th><th>USER NAME</th><th>ASSIGN ROLE</th><th>Add</th></tr>'; 
    $tb .= '</thead><tbody>' . $str . '</tbody></table>';


    //return json_encode($configs);

}

the $str function is what holds the constructed table data... and i echo the table to the page directly into the div tag with id " panel_data_tb ", which is done on the javascript file..

function showAppUser() {
    $('.loading').css('display', 'block');
    var appID = $('#app_search').val();
    $.ajax({
        method: 'get',
        url: getauprofile,
        data: {appId: appID}
    })
        .done(function (result) {
           // alert('success '  + result);
           $('#panel_data_tb').html(result);
            $('.loading').css('display', 'none');


            //this line here is what initializes the datatable on the 
            //current table just being created... 
            //dynamically.. and it worked. perfectly for me.. 
            //******************************************************

            $('#panel_data_tb').find('table').DataTable();

            //*******************************************************


        });

}

the last line.. finds the table within the Div tag and initializes the datatable() property on it dynamically. so anytime you change the contents of the table, the datatable is re-initialized on the dynamic table being created..

i hope this helps. thanks.

Ande Caleb
  • 1,163
  • 1
  • 14
  • 35