Reload or Refresh Datatables

Asked

Viewed 1,251 times

3

Good morning,

I have a Datatables that is loaded by a WHILE coming from a QUERY in which I mount at the beginning of my page by PHP.

My problem is when I need to insert or edit some information that goes into this table in HTML, because I can’t refresh the whole page only in Table and that would be my problem.

Someone would know how to load the information that comes from this QUERY in PHP to my Table again?

I make the call of insertion or editing by AJAX and would like that to happen in the request SUCCESS.

inserir a descrição da imagem aqui

Montage of my Table: Cadastro de Acesso

                                                <!-- MONTAGEM DO CABEÇALHO DA TABLE -->
                                                <thead>
                                                    <tr class="bg-light">                                                          
                                                        <th>Cód. Acesso</th>
                                                        <th>Crachá OBER</th>
                                                        <th>Tipo Operação</th>
                                                        <th>Tipo Transporte</th>
                                                        <th>Placa do Veículo</th>
                                                        <th>Nome Empresa</th>
                                                        <th>Está na Empresa?</th>
                                                        <th>Cod. Autorizador</th>
                                                        <th>Nome Autorizador</th>
                                                        <th>Cód. Depto. Autor.</th>
                                                        <th>Nome Depto. Autor.</th>
                                                        <th>Dt. Entrada</th>
                                                        <th>Dt. Saída</th>
                                                        <th>Dt. Liberação</th>
                                                        <th>Dt. Limite Libe.</th>
                                                    </tr>
                                                </thead>
                                                <!-- FIM DO CABEÇALHO -->


                                                <!-- MONTAGEM DO CORPO DA TABLE -->
                                                <tbody>
                                                    <?php while (oci_fetch($stid_tables)) { ?>
                                                        <tr ng-repeat="ln in lista" class="ng-scope">                                                               
                                                        <td><?php echo $COD_ACESSO2; ?></td>
                                                        <td><?php echo $COD_CRACHA_OBER; ?></td>
                                                        <td><?php echo $TIPO_OPERACAO; ?></td>
                                                        <td><?php echo $DESC_TIPOTRANSPORTE; ?></td>
                                                        <td><?php echo $PLACA_VEICULO; ?></td>
                                                        <td><?php echo $NOME_EMPRESA; ?></td>
                                                        <td><?php echo $ATIVO_NAEMPRESA; ?></td>
                                                        <td><?php echo $COD_AUTORIZADOR; ?></td>
                                                        <td><?php echo $NOME_AUTORIZADOR; ?></td>
                                                        <td><?php echo $COD_LOCALIZACAO; ?></td>
                                                        <td><?php echo $DPTO_AUTORIZADOR; ?></td>
                                                        <td><?php echo $DT_ENTRADA; ?></td>
                                                        <td><?php echo $DT_SAIDA; ?></td>
                                                        <td><?php echo $DT_LIBERACAO; ?></td>
                                                        <td><?php echo $DT_LIMITELIBERACAO; ?></td>
                                                        </tr>
                                                    <?php } ?> 
                                                </tbody>
                                                <!-- FIM DO CORPO -->
                                            </table>

Mounting of my AJAX:

            //FUNÇÃO DE INSERIR E EDITAR CADASTRO DE ACESSO
            $("#btnInserirAcesso").click(function() {
                //VARIAVEL DE CONTROLE DE INSERÇÃO DE NOVO ACESSO OU SE É EDIÇÃO DE UM ACESSO JÁ EXISTENTE
                var INSERIR_NOVO = $INSERIR_NOVO_ACESSO;

                $("<input />").attr("type", "hidden").attr("name", "COD_VISITANTE2").attr("value", "<?php print $COD_VISITANTE ;?>").appendTo("#cadAcesso");
                $("<input />").attr("type", "hidden").attr("name", "RH_IN_FILIAL").attr("value", "<?php echo $RH_IN_FILIAL; ?>").appendTo("#cadAcesso");
                $("<input />").attr("type", "hidden").attr("name", "RH_IN_MATRIZ").attr("value", "<?php echo $RH_IN_MATRIZ; ?>").appendTo("#cadAcesso");
                $("<input />").attr("type", "hidden").attr("name", "ERP_IN_FILIAL").attr("value", "<?php echo $ERP_IN_FILIAL; ?>").appendTo("#cadAcesso");
                $("<input />").attr("type", "hidden").attr("name", "COD_USUARIO").attr("value", "<?php echo get_info_session(2, 'USU_IN_CODIGO'); ?>").appendTo("#cadAcesso");

                //EDITAR CADASTRO
                if ( INSERIR_NOVO == 'N' ) {
                    if (confirm('Tem certeza que deseja alterar este registro?')) {
                       $("<input />").attr("type", "hidden").attr("name", "ACAO").attr("value", "UA").appendTo("#cadAcesso");

                        var formData = new FormData(document.querySelector('#cadAcesso'));

                        $.ajax({url: '<?php echo $path_dir;?>apps/portaria/crud.php',
                                type: 'POST', 
                                data: formData,
                                dataType: 'html',
                                mimeType:"multipart/form-data",
                                processData: false,
                                cache: false,
                                contentType: false,

                                //RETORNO OK
                                success: function(data) {
                                    if ( data == 'OK' ) {
                                        alert('Acesso Nº[' + document.getElementById("inputCodAcesso").value + '] alterado com sucesso!'); 

                                        //location.reload();  
                                        //$('#tabela_cadvisit').ajax.reload();                           
                                    } else {
                                        alert(data);
                                    };  
                                },

                                //RETORNO ÑOK
                                error: function(xhr, ajaxOptions, data) {
                                    alert('erro');
                                }
                        });

                        return false; 
                    } else {
                        return false;
                    };
  • What is the return of data in the Success?

  • @Sam is always 'OK' if positive. V_TXT_RETORNO := 'OK'; RETURN(V_TXT_RETORNO); . In crud.php I call all my database changes.

  • I understand, but where do you edit or insert table data?

  • Always handled by the database, in case of some kind of error in the execution of INSERT for example, the database returns me a STRING already with the requested error in the database. In the case of error-free execution I only issue a return OK.

  • I asked where you edit or insert data in datatables. Have some form for this?

  • Yes for this <form enctype="Multipart/form-data" id="cadAccess" method="POST">

  • Blz, the question of inserting is quiet to do, but the question of "editing" is more complicated. How you are selecting the line you want to edit and how you are pulling the information from this line?

  • For editing I am in the btnEditar click by selecting the key of my table like this, by JS: if ( $("#table_cadvisit tr.Selected"). length >= 1 ) { I call an AJAX that in this CRUD.PHP I run a QUERY and in Success I insert the values in the fields of my modal $('#inputCodAccess'). val(data.COD_ACESSO2); Returned by datatype:'json'. In the end I give a modal(show)

  • @Sam forgot to comment on the description of my question, that I need to refresh or re-load on Datatables when I get out of my modal. The Success I referred to in the question is my modal’s Insert Success that opens when I click insert or edit. Sorry for the lack of information.

Show 4 more comments

1 answer

0


Here’s what you’re gonna do:

The PHP code that loads data from the datatables (where it has <?php while (oci_fetch($stid_tables)) { ?>) you will put in a file .php separate and make a include in tbody:

<tbody>
  <?php include ('tabela.php'); ?>
</tbody>

That same file .php will be where you will make an AJAX to reload the table after closing the insert or edit modal.

When closing the modal, call the function below:

function recarregar(){
   $('#example tbody').load("tabela.php", function(data){
      $('#example').DataTable().destroy();
      $('#example tbody').empty().append(data);
      $('#example').DataTable();
   });
}

The function will destroy the datatables, empty the tbody, insert the updated data and start the plugin again.

In the archive .php, to do the while, you will need to query the database to return the data.

  • Good afternoon Sam. To load Datatables worked perfectly, but when I call reload() inside my AJAX Success in my modal’s Insert/Edit, it does not run LOAD: $('#tbodyCadVisit tbody'). (load'<? php echo $path_dir;? >apps/portaria/visitantes_veiculos/tbody_cad_visit.php', Function(data){ But I also don’t get any errors. See below what I’m doing in code.

  • Good morning, buddy. Put a console.log(data) in . load’s Function to see what shows the console.

  • See also what version of jQuery you are using.

  • Good afternoon Sam. I managed to call my file. PHP with QUERY to load Datatable again, only when loading the Table body again, the header loses the initial configuration of the data and is misaligned with the Table body.

  • See how I am running inside LOAD: $('#tabela_cadvisit'). remove(); $('#tabela_cadvisit'). Datatable(). Destroy(); $('#tabela_cadvisit tbody'). Empty(). append(data); $('#tabela_cadvisit'). Datatable({});

  • 1

    Vc tah removing the element, so it will give error even

  • Sam good morning, now it’s working properly, thank you so much for your help.

Show 2 more comments

Browser other questions tagged

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