0

I need to append a DataTable dynamically, I need to fill a form several times and show results in a DT each time a user clicks on the button to send results of their inputs and show the results in my Datatable.

 <table id="table" class="display" width="100%"></table>
 <button type="button" id="btnOne" class="btn btn-success"> Valider</button>

 <script>
 $("#btnOne").click(function() {
     var reje = $("#table")

    reje.DataTable ({
        "data" : maj_ref_modeles_json,
        "columns" : [
            { "data" : "codemodele" },
             { "data" : "pksegmentation" }

        ]
    });
 });
 </script>

The datatable is filled correctly for the first set of data, but at the second iteration, I have this message in my browser :

DataTables warning: table id=table - Cannot reinitialise DataTable. For more information about this error, please see http://datatables.net/tn/3

userHG
  • 567
  • 4
  • 29
  • did you already see this? https://stackoverflow.com/questions/13708781/datatables-warningtable-id-example-cannot-reinitialise-data-table – luna80 Mar 13 '20 at 13:01

1 Answers1

0

Destroy datatable before creating new

$("#table").dataTable().fnDestroy();
this.girish
  • 1,296
  • 14
  • 17
  • wouldn't this remove the previous data as well? , from what i interpret from "I need to append a DataTable dynamically" the OP wants to keep appending the data to the table – Abdullah Abid Mar 13 '20 at 13:21
  • I alredy used this and got an error : jquery.dataTables.min.js:79 Uncaught TypeError: Cannot read property 'aDataSort' of undefined – userHG Mar 13 '20 at 13:30
  • Then problem lies in your tbody you need to empty tbody using $(`#table tbody`).empty(); try this – this.girish Mar 13 '20 at 13:34
  • Same problem, Cannot reinitialise DataTable – userHG Mar 13 '20 at 13:52