Popular Datatables via a JSON variable

Asked

Viewed 1,129 times

0

I have the following function that returns data from a query in the database and stores in json format in the msg variable.

$.ajax({
        type: 'POST',
        dataType: 'html',
        url: page,

        data: {idtabela: idtabela},
        success: function (msg) {
            msg = $.parseJSON(msg);
 }
});

In my front-end file, I need to popular this table. I am using the Datatables plug

<table width="100%" class="table table-striped table-bordered table-hover" id="dataTables-example">
                                <thead>
                                    <tr>
                                        <th>Cliente</th>
                                        <th style="width: 50px">Carro</th>
                                        <th style="width: 50px">Data</th>
                                        <th style="width: 150px">Ações</th>
                                    </tr>
                                </thead>
                                <tbody>

                                    <tr class="odd gradeX">
                                        <td>> </td>
                                        <td> </td>
                                        <td> </td>
                                        <td style="text-align: center">
                                            <a class="btn btn-primary btn-sm" href="edit.php?id=1" role="button">Editar</a>
                                            <input type="button" value="Excluir" class="btn btn-danger btn-sm""/>
                                        </td>
                                    </tr>

                                </tbody>
     </table>

jquery function for the datatables plugin

$(document).ready(function() {
    $('#dataTables-example').DataTable({
        language:{
            url: '../includes/datatable_ptbr.json'
        },
        responsive: true
    });
});

1 answer

0

The most advisable is you refatora to make the request ajax in the datatable even according to the manual: https://datatables.net/examples/ajax/objects.html

$(document).ready(function() {
  $('#example').DataTable( {
    "ajax": "data/objects.txt",
      "columns": [
        { "data": "name" },
        { "data": "position" },
        { "data": "office" },
        { "data": "extn" },
        { "data": "start_date" },
        { "data": "salary" }
     ]
   });
 });

Browser other questions tagged

You are not signed in. Login or sign up in order to post.