Mario Cordeiro
Mario Cordeiro

Reputation: 125

Data disappears after populating the data

I have this DataTable:

<table class="table table-striped table-bordered table-advance table-hover" id="tabela_1">
    <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
        </tr>
    </thead>

    <tbody>
        <tr>
            <td></td>
            <td></td>
        </tr>
    </tbody>
</table>

I want to fill the table with data, using AJAX call. I have the following AJAX code:

function SearchResult(){

      $.ajax({
          url: 'php/search.php,
          type: 'get',
          data: $("#form_search").serialize(),
          dataType: 'json',
          success: function (data) {
            if (data.success) {
                $("#tabela_1 > tbody").html("");
                $.each(data, function (index, record) {
                  if ($.isNumeric(index)) { 
                    var row = $("<tr />");
                    $("<td />").text(record.ID).appendTo(row);
                    $("<td />").text(record.name).appendTo(row);
                    row.appendTo('#tabela_1');
                  }
                });
            }
          }
        });
    }

At this point I get the table filled (after calling the SearchResult() function).

But, when I press the table column to sort that column, all the data disappear. The same happens when I use the table search box. I've tried to use the fnDraw() and fnUpdate() but with no effect.

Upvotes: 0

Views: 1040

Answers (1)

Gyrocode.com
Gyrocode.com

Reputation: 58880

It's not recommended to use <tr>/<td> nodes to add data to the table, use appropriate DataTables API methods instead, for example row.add().

JavaScript:

success: function (data) {
   var table = $("#tabela_1").DataTable();

   if (data.success){
      table.clear();
      $.each(data, function (index, record){
         if ($.isNumeric(index)) {
            table.row.add([record.ID, record.name]);
         }
      });

      table.draw();
   }
}

HTML:

<table class="table table-striped table-bordered table-advance table-hover" id="tabela_1">
    <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
        </tr>
    </thead>
</table>

Upvotes: 1

Related Questions