Re-initialize dataTable from fnServerData

Re-initialize dataTable from fnServerData

balnysbalnys Posts: 10Questions: 1Answers: 0
edited September 2014 in DataTables 1.9

Datatable is being initialized with 2 ajax calls: table structure (columns) and table data.
Structure data is being cached.

Case:
User removes last records from table
Table being initialized (reDrawn)
Re-cache table structure

    // 1) Get table structure
    // 2) render table 
    // 3) initialize dataTable
// If there are any records, structure is cached in localStorage()
function setupTable() {
    function getStructure() {

      if (response.iTotalRecords > 0) 
        localStorage.setItem(structureName, JSON.stringify(response));

    }
    oTable.renderTable(); // render table structure in document
    oTable.initTable();
}

function initTable() {  
    function fnServerData() {
      // If has cached structure but doesn't have records
              // -> setup dataTable with fresh structure
          if (iTotalRecords === 0 && hasCachedStructure()) {

      // step 1) Remove old cached structure
      localStorage.removeItem(structureName);

       // step 2) Destroy table before initializing it again
       oTable.fnDestroy();

       // step 3) Get new structure and initialize datatable with new structure
       setupTable();

      }
    } 
}

The issue is that dataTable controls (column, pagination, footer info) is not being destroyed.
How can I do clean table destruction and setup table from start?

Thank you for your time and any guidance.

Answers

  • balnysbalnys Posts: 10Questions: 1Answers: 0
    edited September 2014

    If I clear content of table wrapper like:

    // step 2) Destroy table before initializing it again
    oTable.fnDestroy();
    $('.dataTableWrapper').empty();
    

    I'm getting:

    TypeError: $(...)[0] is undefined
    $('.dataTables_paginate')[0].style.display = "none";
    
  • balnysbalnys Posts: 10Questions: 1Answers: 0

    I ended by removing controls one by one, like:

    // step 2) Destroy table before initializing it again
    oTable.fnDestroy();
    $('.dataTableWrapper').empty();
    $('.table-wrapper').siblings('.table-controls-bottom, .table-controls').remove();
    
  • allanallan Posts: 63,679Questions: 1Answers: 10,498 Site admin

    Yes - you would use destroy() to destroy the old table before creating a new one.

    Allan

This discussion has been closed.