Create a table with sorting using DataTable

4

I am creating a table and need to give the option to sort the table by the field of your choice. I tried to use the dataTable the data is padded correctly in the table but when I click on a header to sort, filter, or any other function of the dataTable the table data pops up and the message appears:

No data available in table

My codes:

HTML

<div class="table-responsive">
    <table id="tableTarefas" class="table table-bordered table-hover table-striped">
        <thead>
            <tr>
                <th>Nome</th>
                <th>Grau</th>
                <th>Data</th>
                <th>Descrição</th>
                <th>Tempo de execução</th>
                <th>Informações adicionais</th>
            </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
</div>

JS

$("#tableTarefas").dataTable();

$.ajax({
    type: "get",
    url: rootUrl + "tarefas/listAll" + updat,
    dataType: "json",
    success: function(data)
    {
        $("#tableTarefas").find("tbody tr").remove();
        data.result.forEach(function(tarefa)
        {
            row= "<tr>"
                    + "<td><a id='edit' href='#' data-id='" + tarefa.id_tar + "'>"+ tarefa.non_tar + "</a></td>"
                    +      "<td>"+ tarefa.gra_tar + "</td>"
                    +      "<td>" + tarefa.datf_tar + "</td>"
                    +      "<td>" + tarefa.des_tar + "</td>"
                    +      "<td>" + tarefa.tee_tar + "</td>"
                    +      "<td>" + tarefa.inf_tar + "</td>"
                    + "</td></tr>";

            $("#tableTarefas > tbody:last").append(row);
        });
    },
    error: function(result)
    {
        $("#errorLoad").html(getErrorMessage(result.responseText));
        $("#errorLoad").show();
        $("#tableTarefas").find("tbody tr").remove();
    }
});

Web service return: (2 rows)

{
  "result":[
    {
      "id_tar":"24",
      "non_tar":"trtyr",
      "gra_tar":"10",
      "tee_tar":"00:00:00",
      "dati_tar":"2015-11-14",
      "datf_tar":"0000-00-00",
      "datd_tar":"2015-11-15",
      "des_tar":"",
      "con_tar":"0",
      "idu_tar":"1",
      "idud_tar":null,
      "inf_tar":"",
      "pts_tar":"0"
    },
    {
      "id_tar":"42",
      "non_tar":"asdas",
      "gra_tar":"1",
      "tee_tar":"00:00:00",
      "dati_tar":"2015-11-15",
      "datf_tar":"0000-00-00",
      "datd_tar":"2015-11-15",
      "des_tar":"",
      "con_tar":"0",
      "idu_tar":"1",
      "idud_tar":null,
      "inf_tar":"",
      "pts_tar":"0"
    }
  ]
}

Does anyone know how to solve this problem?

    
asked by anonymous 15.11.2015 / 19:54

2 answers

1

Unfortunately you will need to use the DataTables API, here is a complete example of using all functions / options. what you will need.

Give emphasis to options columns , event fnRowCallback and calls oTable.row.add({}) , oTable.clear() and oTable.draw() ;

  • options columns is used to define the format of your model, ie the properties of your json object.
  • fnRowCallback is for modifying the DOM before inserting into the table.
  • DataTable.clear() is used to clear the table.
  • DataTable.row.add({}) add new records.
  • or DataTable.draw() "reloads" the DataTable.

faker.locale = "pt_BR"

var dataLimite = new Date("Sat Sep 20 1992 21:35:02 GMT+0200 (CEST)");
var tableTarefas = $("#tableTarefas");
var btSource = $("#btSource");

var mockPessoas = function () {
  var pessoas = [];
  for (var indice = 0; indice < 20; indice++) {
    var pessoa = {};
    var firstName = faker.name.firstName();
    var lastName = faker.name.lastName();

    pessoa.id = indice;
    pessoa.nascimento = faker.date.past(50, dataLimite).toLocaleDateString();  
    pessoa.nome =  faker.name.findName(firstName, lastName);

    pessoa.endereco = faker.address.streetAddress();
    pessoa.cidade = faker.address.city();
    pessoa.estado = faker.address.stateAbbr();
    pessoa.cep = faker.address.zipCode();
    pessoa.pais = faker.locales[faker.locale].address.default_country;
    pessoa.phone =  faker.phone.phoneNumber();
    pessoa.username =  faker.internet.userName(firstName, lastName);
    pessoa.senha =  faker.internet.password();
    pessoa.email =  faker.internet.email(firstName, lastName);
    pessoas.push(pessoa);
  }
  return pessoas;
}

var oTable = tableTarefas.DataTable({
  "columns": [
    { "data": "nome", "name": "Nome",   "targets": 0 },
    { "data": "nascimento", "name": "Nascimento",  "targets": 1 },
    { "data": "endereco", "name": "Endereco", "targets": 2 },
    { "data": "cidade", "name": "Cidade",  "targets": 3 },
    { "data": "estado", "name": "Estado",    "targets": 4 },
    { "data": "pais", "name": "Pais",  "targets": 5 },
    { "data": "cep", "name": "Cep", "targets": 6 },
    { "data": "phone", "name": "Phone",  "targets": 7 },
    { "data": "username", "name": "Username",    "targets": 8 },
    { "data": "senha", "name": "Senha",  "targets": 9 },
    { "data": "email", "name": "Email", "targets": 10 }
  ],
  "fnRowCallback": function(linha, data) {
    var link = document.createElement("a");
    link.id = "edit";
    link.href = "#";
    link.dataset.id = data.id;
    link.textContent = data.nome;
    linha.cells[0].textContent = "";
    linha.cells[0].appendChild(link);
  }
});

var atualizarPessoas = function () {
  var pessoas = mockPessoas();  
  pessoas.forEach(function (pessoa, indice) {
    oTable.row.add(pessoa);
  });
  oTable.draw();
}

atualizarPessoas();
btSource.on("click", function () {
  oTable.clear();
  atualizarPessoas();
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/material-design-lite/1.1.2/material.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.11/css/dataTables.material.css" rel="stylesheet"/>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/Faker/3.0.1/faker.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/material-design-lite/1.1.2/material.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.11/js/jquery.dataTables.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.11/js/dataTables.material.js"></script><buttonid="btSource" class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--accent">Mudar Lista de Pessoas</button>
<div class="table-responsive mdl-data-table">
  <table id="tableTarefas" class="table table-bordered table-hover table-striped">
    <thead>
      <tr>
        <th>Nome</th>
        <th>Nascimento</th>
        <th>Endereco</th>
        <th>Cidade</th>
        <th>Estado</th>
        <th>Pais</th>
        <th>Cep</th>
        <th>Phone</th>
        <th>Username</th>
        <th>Senha</th>
        <th>Email</th>
      </tr>
    </thead>
    <tbody>
    </tbody>
  </table>
</div>
    
17.03.2016 / 13:45
0

You can try to apply the DataTable after the table has the data, but the correct one to add rows to a Datatable table, is not to use append, it's the datatables API itself: link

    
01.12.2015 / 17:44