How to append ajax result in modal with datatable

Robert

New Member
#1
Good day everyone! I am trying to append my ajax result in my datatable inside my modal. I already get the data that I needed but it still shows that data is not available.
It shows like this:

mxdY4.png

This is my ajax success which processed the result.
Mã:
    success: function(result)
    {
      //console.log(result);
      //$('#viewTable').empty();
      $.each(result, function(index, value){
        console.log(value);

        $('#viewTable').append(
         '<tbody>' +
             '<tr>' +
                '<td>' + value.qr_code + '</td>' +
                '<td>' + value.reference_no + '</td>' +
                '<td>' + value.brand_name + '</td>' +
                '<td>' + value.model_name + '</td>' +
                '<td>' + value.unitPrice + '</td>' +
             '</tr>' +
          '</tbody>'
          );
      });
This is my HTML
Mã:
        <table id="viewTable" class="table table-striped">
          <thead>
            <tr>
              <th>Barcode</th>
              <th>Reference Number</th>
              <th>Brand Name</th>
              <th>Model Name</th>
              <th>Unit Price</th>
            </tr>
          </thead>
        </table>
Note: When I uncomment the "$('#viewTable').empty();" function it will remove my thead (Datatable).
Thanks!
 

Admin

Administrator
Thành viên BQT
#2
First store the dataTable object in a variable,
Mã:
var dataTable = $("#viewTable").DataTable();
Then on ajax success, use dataTable.add([" "," ", " "]).draw(), wherein dataTable is the variable name.

To clear the data table use dataTable.clear();
Mã:
dataTable.clear().draw();
See code below;
Mã:
success: function(result) {
  // store your data table object in a variable
  var dataTable = $("#viewTable").DataTable();
  /////////////////////////////////////////////
  dataTable.clear().draw();

  $.each(result, function(index, value) {
    console.log(value);

    // use data table row.add, then .draw for table refresh
    dataTable.row.Add([value.qr_code, value.reference_no, value.brand_name, value.model_name, value.unitPrice]).draw();
  });
}
 
Top