destroy table whild using dynamic columns

destroy table whild using dynamic columns

nbalelinbaleli Posts: 2Questions: 1Answers: 0
edited May 2015 in Free community support

Im creating column names dynamically, according to the json format received from the server.
it works as expected.
upon user interaction, I need to re-create the table, with different data.
im trying to 'destroy' the table before instatinating the new one,
need your help with the right syntax.

this is how I use the plugin (working):

Api.getDeposits(formData).then(function(res){
    var columns = [];
    Object.keys(res[0]).forEach(function(key){
      columns.push({
        data: key,
        title: key
      })
    });

    $('#searchResults').DataTable().destroy();
    // $('#searchResults').empty();

    var table = $('#searchResults').DataTable( {
      "destroy": true,
      "data": res,
      "scrollX": "100%",
      "columns": columns
    });
  });

when tying to re-create the table, with data with different column count, I get an error:

Uncaught TypeError: Cannot read property '_setter' of undefined

when trying to manually destroy the table, i need to do this:

$('#searchResults').DataTable().destroy();

and get this error:

Uncaught TypeError: Cannot read property 'aDataSort' of undefined

can someone point to the right way to go about this situation? thank you.

Answers

  • leddyleddy Posts: 16Questions: 5Answers: 1

    I use this and it works for me

    $('#searchResults').dataTable().fnDestroy();
    
  • allanallan Posts: 61,726Questions: 1Answers: 10,109 Site admin

    @nbaleli - Can you link to a test case showing the issue please? Your code looks like it should work okay - with the empty() call back in.

    Allan

  • nbalelinbaleli Posts: 2Questions: 1Answers: 0
    edited May 2015

    sorry I forgot to mention, my HTML contained only the <table> element. the columns are created dynamically after the ajax call. that's the reason I couldn't initialize the table with empty config object.

    I fixed it by defining a hoisted 'table' variable at the top, and referencing it when ever a new ajax call is made:

    $(document).ready(function() {
      var table;
    
      $('#searchBtn').click(function(e){
        e.preventDefault();
    
        .....
    
        Api.getDeposits(formData).then(function(res){
          var columns = [];
    
          if (res[0]) {
            Object.keys(res[0]).forEach(function(key){
              columns.push({
                data: key,
                title: key
              })
            });
    
            if (table) { 
              table.destroy(); 
              $('#searchResults').empty();
            }
    
            table = $('#searchResults').DataTable( {
              "destroy": true,
              "data": res,
              "scrollX": "100%",
              "columns": columns
            });
          }
    
          ...
        });
      })
    
    });
    
This discussion has been closed.