Problem in Reload Table Using AJAX

Asked

Viewed 492 times

1

Good morning,

I am using Datatable and loading my data via Ajax from Datatable itself but I would like to give Reload updating the table with the new data from the database

However, the table is loaded completely right but I put a setInterval that every 30 seconds of an ajax.Reload in the Table, in the meantime I make a change in the database but load the setInterval not from the reload in the table...

$(document).ready(function() {
            var base_url = $(".url_base").val();
            function decode_utf8(s) {
                return decodeURIComponent(escape(s));
            }
        var table;  
            $.fn.dataTable.moment( 'DD/MM/YYYY HH:mm:ss' );
            table = $('#logacesso').DataTable({
               "language" : {
                    "sEmptyTable": "Nenhum registro encontrado",
                    "sInfo": "Mostrando  _START_ até _END_ de _TOTAL_ Resultados",
                    "sInfo": "Mostrando de _START_ até _END_ de _TOTAL_ registros",
                    "sInfoEmpty": "Mostrando 0 até 0 de 0 registros",
                    "sInfoFiltered": "(Filtrados de MAX registros)",
                    "sInfoPostFix": "",
                    "sInfoThousands": ".",
                    "sLengthMenu": "_MENU_ resultados por página",
                    "sLoadingRecords": "Carregando...",
                    "sProcessing": "Processando...",
                    "sZeroRecords": "Nenhum registro encontrado",
                    "sSearch": "Pesquisar",
                    "oPaginate": {
                        "sNext": "Próximo",
                        "sPrevious": "Anterior",
                        "sFirst": "Primeiro",
                        "sLast": "Último"
                    },
                    "oAria": {
                        "sSortAscending": ": Ordenar colunas de forma ascendente",
                        "sSortDescending": ": Ordenar colunas de forma descendente"
                    }
                },
                dom: 'Bfrtip',  
                buttons: [
                    'copyHtml5',
                    'excelHtml5',
                    'csvHtml5'
                ],
               "order": [[ 2, 'desc' ]],
               "ajax": {
                    "jQueryUI": true,
                    "processing": true,
                    "serverSide": true,
                    "url": base_url+'painel/Logacesso/totalLogs',
                    "type": "POST",
                    "dataSrc": function( json ){

                        var return_data = new Array();

                        for(var i=0; i<json.length; i++) {


                            var data_1 = json[i]['datahora_log'].substring(0,10);

                            var hora = json[i]['datahora_log'].substring(10,19);

                            var data_2 = data_1.split('-').reverse().join('/') + hora;

                            var cidade = decode_utf8(json[i]['cidade_log']);


                            return_data.push({

                              'codigo_log': json[i]['codigo_log'],
                              'ip_log' :  json[i]['ip_log'],
                              'datahora_log' : data_2,
                              'cidade_log' : cidade,
                              'estado_log' : json[i]['estado_log'],
                              'email_usu' : json[i]['email_usu'],
                              'razao_usu' : json[i]['razao_usu'],
                            })
                        }

                        return return_data;
                    }
                  },
                "aoColumns": [
                    { "data": 'codigo_log' },
                    { "data": 'ip_log' },
                    { "data": 'datahora_log' },
                    { "data": 'cidade_log' },
                    { "data": 'estado_log' },
                    { "data": 'email_usu' },
                    { "data": 'razao_usu' }
                ]   
            });

        setInterval( function () {
            alert("reload");
            table.ajax.reload();
            }, 30000 );
        });
  • Have you tried to place your table inside a function. and call it inside the setInterval ? in place of table.ajax.reload();

  • But in case I would also like to put a button so that it reaload in the table.

  • you can do that too. and just put a action that when you click update call the function again

  • take a look at this example: https://datatables.net/extensions/select/examples/initialisation/reload.html

1 answer

0

There’s an easy solution to this, buddy !

You initialize the data table first of all with the data.

$('#data-table').DataTable();

Right ??

After initialization, you can make an ajax request that will return a json, and recreate the table.

Let’s assume that the object date, is the json returned from ajax and you want to update it in the data table.

var objs = {
 columns: [
    {data:"Nome"},
  {data:"Sobrenome"},
 ],
 data: data,
}

You create an object that will be updated by passing the data parameter: with the json data returned ! and setting the columns ! (remember, the column names must be equal to the ones returned by json)

Now you just recreate

$('#data-table').DataTable(objs);

Note: the objs object must have all the settings that the data table will have again.

Browser other questions tagged

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