How to refresh the table without using json?

How to refresh the table without using json?

rodrigoasnrodrigoasn Posts: 5Questions: 1Answers: 0

Hello all,

i am not using json to create my table.
i am just making a SELECT on the database and after that i call the html table with the data.

so my doubt is... i would like to refresh my table after an insert, because i need everytime to refresh my page to data appear.

i know how to do it with json, but it will be more fast and productive for me if i have a way to do it without using json!

var table = $('#table_id').DataTable({

    "lengthMenu": [[15, 50, 100, 150, -1], [15, 50, 100, 150, "Todos"]],
    "stateSave": true,//salva a posição da tabela(paginação ou consulta) ao dar refresh.
    "language": {

        "sProcessing":   "A processar...",
        "sLengthMenu":   "Mostrar _MENU_ registros",
        "sZeroRecords":  "Não foram encontrados resultados",
        "sInfo":         "Mostrando de _START_ até _END_ de _TOTAL_ registros",
        "sInfoEmpty":    "Mostrando de 0 até 0 de 0 registros",
        "sInfoFiltered": "(filtrado de _MAX_ registros no total)",
        "sInfoPostFix":  "",
        "sSearch":       "Procurar:",
        "sUrl":          "",
        "oPaginate": {
            "sFirst":    "Primeiro",
            "sPrevious": "Anterior",
            "sNext":     "Seguinte",
            "sLast":     "Último"
        },

        "buttons":{
            "copy":      "Cópiar",
            "excel":     "Excel",
            "pdf":       "PDF",
            "print":     "Imprimir",
            "colvis":    "Colunas Visíveis",
        }
     },

    "processing": true,

     "columns": [
            { width: "5%" },//SEL
            { width: "5%" },//ALT
            { width: "5%" },//DEL
            { width: "85%" },//DESCRIÇÃO
          ],    

     "createdRow": function ( row, data, index ) {
          //AJUSTA ALINHAMENTO DOS DADOS NA TABELA
          $('td', row).eq(0).addClass('p-1 text-left');//CHECKBOX
          $('td', row).eq(1).addClass('p-1 text-left');//ALT
          $('td', row).eq(2).addClass('p-1 text-left');//DEL
          $('td', row).eq(3).addClass('p-1');//DESCRIÇÃO
     }

});

So, this is the code of my table and i am not using json!

thank you all.

Answers

  • colincolin Posts: 15,118Questions: 1Answers: 2,583

    Are you inserting the row with Editor? Are how is the SQL making it's way into the table?

    Colin

  • rodrigoasnrodrigoasn Posts: 5Questions: 1Answers: 0
    edited May 2020
    <table id="tabela_itens" class="table table-striped table-hover table-responsive-sm table-sm" style="width: 100%">
                        <thead style="width: 100%">
                          <tr>  
                            <th data-orderable="false">
                            <div class="custom-control custom-checkbox">
                             <input type="checkbox" class="custom-control-input">      
                            </div>
                            </th>
                            <th data-orderable="false">Checar</th>  
                            <th data-orderable="false">Alterar</th>
                            <th data-orderable="false">Deletar</th>
                            <th>Código</th>
                            <th>Classe</th>  
                            <th>Subclasse</th>  
                            <th>Fabricante</th>
                            <th>Referência</th>
                            <th>Situação</th>
                          </tr>
                        </thead>
                        <tbody>
                          <?php 
                            $equip->getEquipamentoTable();
                          ?>  
                        </tbody>
                        <tfoot>
                            <tr>
                                <th></th>
                                <th></th>
                                <th></th>
                                <th></th>
                                <th></th>
                                <th></th>
                                <th></th>
                                <th></th>
                                <th></th>
                                <th></th>
                            </tr>
                        </tfoot>
                      </table>
    

    This is the HTML code of my table.
    Inside of the HTML code i call a PHP function that write the rows of the table with a SELECT.

    public function getEquipamentoTable(){
        $query = mysqli_query($this->con->getCon(), "SELECT * FROM TABLE");
    
        while($dados = mysqli_fetch_array($query)){
               <td class='pt-2'>$dados[nu_item]</td>
           <td class='pt-2 text-uppercase'>$dados[te_classe]</td>
           <td class='pt-2 text-uppercase'>$dados[te_subclasse]</td>
           <td class='pt-2 text-uppercase'>$dados[te_fabricante]</td>
           <td class='pt-2 text-uppercase'>$dados[te_referencia_modelo]</td>
               ...
        }
    }
    

    As you can see i draw the rows of the table with a while.
    so i use like that and works perfectly and i would like to keep like that!

    Are you inserting the row with Editor?
    no, i am using the free version of datatable for a while.
    I created a submit button that after fill all the form i just press it and serialize with javascript. After that i call a php class and insert on database.

    After the inserssion i just need that the datatable refresh to show the new row/data

  • kthorngrenkthorngren Posts: 20,145Questions: 26Answers: 4,736

    What I would to is insert the new row then fetch the row from the DB and return just that row to the client. In the ajax success you can then take the returned row and use row.add() to add it to the Datatable. This is essentially what the Editor would do.

    Kevin

  • rodrigoasnrodrigoasn Posts: 5Questions: 1Answers: 0

    This is my code that call the inserssion
    i did like you said..
    i save all the form data in variables and after i call a PHP insert file that make connection to a class and DB to insert in DB.

    and the return of it i take on ajax success.

    So, can i draw a row into my table with function row.add() without use ajax json?

    $(function($) {
        
        $(document).on('submit','#formCadastro',function(event){
            
            //PREVINE O REFRESH
            event.preventDefault();
        
            //CRIA VARIÁVEIS
            var dados         = $(this).serialize();
            var nu_item       = $("#nu_item").val();
            var id_subclasse  = $('select[name=id_subclasse]').val();
            var te_referencia = $('#te_referencia_modelo').val();
            var id_fabricante = $('select[name=id_fabricante]').val();
            var flag_ativo    = $("input[name='flag_ativo']:checked").val();
            var obs_material  = $('#obs_material').val();
            var id_usuario    = $('#id_usuario').val();
            
            //CHAM FUNÇÃO PARA CONFERIR SE A DESCRIÇÃO FOI DIGITADA
            var conferido = confereForm();
                
            if(conferido == true){
                    
                $("#sucessMsg").removeClass("col-12 alert alert-warning text-center mb-5 invisible").addClass("col-12 alert alert-warning text-center mb-5");
                
                $.ajax({
                    url: 'dist/insert_equipamento.php?nu_item='+nu_item+'&id_subclasse='+id_subclasse+'&te_referencia='+te_referencia+'&id_fabricante='+id_fabricante+'&flag_ativo='+flag_ativo+'&obs_material='+obs_material+'&id_usuario='+id_usuario,
                    type: 'post',
                    data: dados,
                    success: function(resposta){
                        
                        if(resposta){
    
                            setTimeout(function() {
                                $("#sucessMsg").html("<i class='fas fa-check'></i> Equipamento cadastrado com sucesso!").fadeIn();
                            }, 100 );
                            setTimeout(function() {
                                $("#sucessMsg").fadeOut();
                                location.reload();
                            }, 2500 );  
    
                        }
                        
                    }
    
                });
        
            }
            
        });
        
    });
    
  • kthorngrenkthorngren Posts: 20,145Questions: 26Answers: 4,736

    So, can i draw a row into my table with function row.add() without use ajax json?

    Of course. You can use row.add() at any point. The purpose of the above set of steps is that the user will see exactly what was inserted into the DB. If you don't need that then simply just use row.add().

    Kevin

This discussion has been closed.