XVirtusX
XVirtusX

Reputation: 709

How to make datatables to handle Ajax requests?

I want datatables to handle itself the Ajax call to populate it, so I have this config:

$('#tabela-usuario-portal').dataTable({
"responsive": true,
"ordering": false,
"retrieve": true,
"ajax": 'usuario/pesquisaUsuario',
"lengthMenu": [5, 10, 20],
"columns": [
    { "data": "usuario" },
    { "data": "email" },
    { "data": "cpf" }
],
"language": {
    "lengthMenu": "Exibindo _MENU_ por página",
    "zeroRecords": 'Nada',
    "paginate": {
        "previous": "Anterior",
        "next": "Próximo"
    }
},
"dom": 't<"tfooter"pl>'
});

and this HTML:

<table id='tabela-usuario-portal' class="tabelaGrid table-hover">
    <thead>
        <tr>
            <th>usuario</th>
            <th>email</th>
            <th>cpf</th>
        </tr>
    </thead>
</table>

Datables succesfully makes the ajax request, and the following is returned:

[{"id":22,"id_sgp":24539,"cpf":"58287467748","email":"[email protected]","usuario":"terminator","cod_perfil"
:1,"situacao":"A"},{"id":30,"id_sgp":33951,"cpf":"24423229196","email":"[email protected]","usuario":"tetris"
,"cod_perfil":89,"situacao":"A"},{"id":28,"id_sgp":34001,"cpf":"31155957865","email":"[email protected]","usuario"
:"zczc","cod_perfil":89,"situacao":"A"}]

But I'm getting an error:

TypeError: f is undefined

I think I'm almost there, I just have to make the correct reference between data from JSON and his respective place. I already read the docs but couldn't figure it out. Any help would be much appreciated.

Upvotes: 0

Views: 80

Answers (1)

Gyrocode.com
Gyrocode.com

Reputation: 58880

SOLUTION

Add ajax.dataSrc and set it to empty string ('') to match your data structure as shown below:

var table = $('#tabela-usuario-portal').DataTable({
    ajax: {
        url: 'usuario/pesquisaUsuario',
        dataSrc: '' 
    },
    /* ... skipped ... */
});

From the ajax.dataSrc option description:

Note that if your Ajax source simply returns an array of data to display, rather than an object, set this parameter to be an empty string.

DEMO

See this jsFiddle for code and demonstration.

Upvotes: 1

Related Questions