Problem with button evt click on datatable.

Problem with button evt click on datatable.

rodrigoasnrodrigoasn Posts: 5Questions: 1Answers: 0
edited October 2020 in Free community support

hi guys.
i am using datatable with serverside and its load a DELETE button inside the col of the table to make possible the deletation of the selected row,
let's check the code:

I request the table with this script bellow that call a php file with the sql instruction:

// DataTable
    var tableProdutos = $('#tabela_produtos').DataTable( {
        "lengthMenu": [[15, 50, 100, 150, 99999999], [15, 50, 100, 150, "Todos"]],
        "stateSave": true,//salva a posição da tabela(paginação ou consulta) ao dar refresh.
            "buttons":{
                "copy":      "Cópiar",
                "excel":     "Excel",
                "pdf":       "PDF",
                "print":     "Imprimir",
                "colvis":    "Colunas Visíveis",
            }
        },
        "processing": true,
        "serverSide": true, 
        "ajax":{
            url: "dist/select_tbl_entrada_produtos.php?cod_entrada="+cod_entrada
        },  

        //organização da estrutura da tabela (OK)
        "dom": "<'row'<'col-sm-12 col-md-6'l><'col-sm-12 col-md-6'f>>" +
                "<'row'<'col-sm-12'tr>>" +
                "<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7'p>>",

        //colReorder: true, (OK)    
        "columns": [
            { width: "5%" },//BTN DELETE
            { width: "5%" },//CÓDIGO PRODUTO
            { width: "30%" },//DESCRIÇÃO
            { width: "5%" },//UNIDADE
            { width: "5%" },//CONSUMÍVEL
            { width: "5%" },//VALIDADE
            { width: "15%" },//ALMOXARIFADO
            { width: "5%" },//RUA
            { width: "5%" },//ESTANTE
            { width: "5%" },//PRATELEIRA
            { width: "5%", render: $.fn.dataTable.render.number( '.', ',', 2, '' )},//QUANTIDADE ENTRADA
            { width: "5%", render: $.fn.dataTable.render.number( '.', ',', 2, 'R$ ' )},//VALOR UNITÁRIO
            { width: "5%", render: $.fn.dataTable.render.number( '.', ',', 2, 'R$ ' )}//VALOR TOTAL
        ],

        "createdRow": function ( row, data, index ) {
            //AJUSTA ALINHAMENTO DOS DADOS NA TABELA
            $('td', row).eq(0).addClass('p-1 text-center');//DELETAR
            $('td', row).eq(1).addClass('p-1 text-center');//CÓDIGO PRODUTO
            $('td', row).eq(2).addClass('p-1 text-left font-weight-bold');//DESCRIÇÃO PRODUTO
            $('td', row).eq(3).addClass('p-1 text-center');//UNIDADE
            $('td', row).eq(4).addClass('p-1 text-center');//CONSUMÍVEL
            $('td', row).eq(5).addClass('p-1 text-center');//VALIDADE
            $('td', row).eq(6).addClass('p-1 text-center');//ALMOXARIFADO
            $('td', row).eq(7).addClass('p-1 text-center');//RUA
            $('td', row).eq(8).addClass('p-1 text-center');//ESTANTE
            $('td', row).eq(9).addClass('p-1 text-center');//PRATELEIRA
            $('td', row).eq(10).addClass('p-1 text-right text-success font-weight-bold');//QUANTIDADE ENTRADA
            $('td', row).eq(11).addClass('p-1 text-right text-primary font-weight-bold');//VALOR UNITÁRIO
            $('td', row).eq(12).addClass('p-1 text-right text-primary font-weight-bold');//VALOR TOTAL
  
        },

    });//FIM DATATABLE

This is the php file with the sql instruction, this is not the complete code, but i've just posted it to explain better my doubt.
the return (array) of this file is interpretated by the script on the top.

//PHP FILE
//WHILE TO MANIPULATE THE DATA
while($dados = mysqli_fetch_array($query)){
 
//TREATMENT OF DATE
            if($dados['dt_validade'] == '0000-00-00'){
                $dt_validade = '-';
            }else{
                $dt_validade = date('d/m/Y', strtotime($dados['dt_validade']));    
            }
            
            
            //TRANSFORM VALUES FORMAT
            $qtd_atual   = number_format($dados['qtd_atual'], 2, ',', '.'); 
            $qtd_entrada = number_format($dados['qtd_entrada'], 2, ',', '.');
            $vl_unitario = number_format($dados['vl_unitario'], 2, ',', '.');
            $vl_total    = number_format($dados['vl_total'], 2, ',', '.');

            
            //CREATE AN ARRAY
            $subdata = array();
               
            //BTN DELETE <------ THIS BUTTON -------->
            $subdata[] = "<a href='#' id='btnDelP_$dados[id_material_entrada]' class='btn btn-outline-danger btn-circle btn-sm' data-toggle='modal' data-target='#modalDelProduto' data-id='$dados[id_material_entrada]' data-nmmaterial='$dados[nm_material]' data-codmaterial='$dados[cod_material]'>
                <i class='fas fa-fw fa-trash-alt'></i>
            </a>";
             

           //COLS OF THE TABLE 
            $subdata[] = $dados['cod_material']; //CÓDIGO MATERIAL
            $subdata[] = $dados['nm_material']; //DESCRIÇÃO MATERIAL
            $subdata[] = $dados['nm_unidade']; //UNIDADE DE MEDIDA
            $subdata[] = $dados['fl_consumivel']; //CONSUMÍVEL
            $subdata[] = $dt_validade; //VALIDADE//
            $subdata[] = $dados['nm_almoxarifado']; //ALMOXARIFADO
            $subdata[] = $dados['nm_rua']; //RUA
            $subdata[] = $dados['nm_estante']; //ESTANTE
            $subdata[] = $dados['nm_prateleira']; //PRATELEIRA
            $subdata[] = $dados['qtd_entrada']; //QUANTIDADE ENTRADA
            $subdata[] = $dados['vl_unitario']; //VALOR UNITÁRIO
            $subdata[] = $dados['vl_total']; //VALOR TOTAL
            $data[]    = $subdata;
        }

        //RETURN AN ARRAY TO CREATE THE TABLE
        echo json_encode($json_data = array(
            "draw"              =>  intval($request['draw']),
            "recordsTotal"      =>  intval($totalData),
            "recordsFiltered"   =>  intval($totalFilter),
            "data"              =>  $data
        ));

After the creation of the table i can see now the DELETE BUTTON.
When i click on it a modal is opened with a msg to confirm the deletation.
After the confirmation this $POST bellow is executed and the row is deleted.

//JAVASCRIPT FILE
// Fazemos a requisão ajax 
          $.post('dist/delete_entrada_produto.php',{id_material_entrada: id_material_entrada}, 
          function(resposta) {

              //pega o retorno e cria um objeto
              var obj = jQuery.parseJSON(resposta);

              if(obj.msg == 'sucesso'){

                  $("#modalDelProdutoTlt").html("<i class='fas fa-check'></i> Sucesso");

                  setTimeout(function() {
                      $("#sucessMsgDelProduto").html("<i class='fas fa-check'></i> Produto: <b>"+cod_material+' - '+nm_material+"</b> deletado com sucesso!").fadeIn();
                  }, 100 );
                  setTimeout(function() {
                      $("#sucessMsgDelProduto").fadeOut();
                      
                      //ATUALIZA TABELA
                      tableProdutos.ajax.reload();
                  }, 1000 );    
                  

              }

          });

THE PROBLEM IS:
if i click on the DELETE button, the modal opens, but if i don't delete and click again on another button row a new modal will open, but if this time i confirm two rows will be deleted.
is like if the first row were saved in somewhere and when the second row is confirmed both are deleted.
This problem just happend if i don't refresh the page, but my intention is not refreshing the page... so the problem persist. When i refresh is like if the counter that is saving the click were restarted

i don't know if i expressed my doubt good, but the discurssion is opened and i would like to solve it with the help of communit.

thanks all.

Replies

  • kthorngrenkthorngren Posts: 21,343Questions: 26Answers: 4,954

    If I understand correctly you click the delete button in a row and don't delete the row. Then click delete in another row both rows appear in your confirmation message. Sounds like your click event handler isn't handling the case properly by not resetting something. I might be missing it but I don't see your delete button click event handler. Doesn't sound like a Datatables issue but if you want to post that code we can take a look. Better would be a link to your page or a test case showing the issue.

    Kevin

  • rodrigoasnrodrigoasn Posts: 5Questions: 1Answers: 0
    edited October 2020

    No. Is like that:

    when i click the DELETE BUTTON a modal appear like that:

    if i confirm "BLUE BUTTON" the row will be deleted, but if i don't "GRAY BUTTON" the row stays there... if u stop to think... it is working correctly, but the problem is when i don't delete and click in another row to delete and confirm, in this ocasion both rows will be deleted and i don't know why it is happening.

    is like the first one that i clicked and don't delete stays saved the request and this request is processed when i delete another row, so the result of it is that if u have 10 rows and click on delete button in 9 rows, but after you cancel the deletion and in sequence you click at the 10th row and confirm the delete all the rows will be deleted. i think there is a counter in DOM i really don't know where and how to manipulate this counter to not count..

  • kthorngrenkthorngren Posts: 21,343Questions: 26Answers: 4,954
    edited October 2020

    but the problem is when i don't delete and click in another row to delete and confirm, in this ocasion both rows will be deleted and i don't know why it is happening.

    Yes, that is what I understand.

    think there is a counter in DOM i really don't know where and how to manipulate this counter to not count..

    The process and events you are using are custom to your page. They are not provided as part of Datatables. Please post a link to your page or a test case replicating the issue so we can help debug. Screenshots are not enough for us to debug.
    https://datatables.net/manual/tech-notes/10#How-to-provide-a-test-case

    Kevin

This discussion has been closed.