Delete in the database using ajax and jquery

Asked

Viewed 3,514 times

2

Which correct method to be able to delete, my doubt is being how you get the id based on the table row, and how to send it to a page that actually excludes. The codes I’ve already made will be following.

listUsuario.php

    <script type="text/javascript">
$("#elemento-pai-da-tabela").on('click', '.btn_Excluir', function(e){
        e.preventDefault(); 
        var $trPai = $(this).parent().parent(); 
        var id = $trPai.data('id'); 
        $.ajax({ type: "POST", 
            data: { 'COD_IDENT_USUAR': id }, 
            url: "excluirUsuario.php", 
            success: function(msg) { 
                $trPai.remove(); 
            } 
    }); 
}); 
</script>
<?php

    // incluindo o arquivo que faz a conexao com o banco
    include ("../includes/conexao.php");

    // Listando os Cargos

    // executa  query de consulta e armazena o resultado devolvido na variável $resultado
     $resultado = mysql_query("SELECT TXT_NOMEX_USUAR, TXT_ENDER_EMAIL, FLG_STATU_USUAR, DAT_ULTIM_LOGIN, COD_IDENT_USUAR from tbl_USUARIOS");


    // se não existir cargos cadastrados exibe uma mensagem
    if(mysql_num_rows($resultado)<=0)
    {
        echo "<div class='alert alert-error'>";
        echo "<b>Atenção!</b><br>";
        echo "Não existe cargo cadastrado no momento.";
        echo "</div>";
    }

    // se existir produtos cadastrados lista-os
    else
    {
        echo "<table class='table table-striped'>";
        echo "<th class='excluir'>Excluir</th>";
        echo "<th class='alterar'>Alterar</th>";
        echo "<th>Nome</th>";
        echo "<th>Email</th>";
        echo "<th>Status</th>";
        echo "<th>Último Login</th>";

        while($linha = mysql_fetch_array($resultado))
        {
            echo "<tr data-id='$linha[4]'>";
            echo "<tr>";
            echo "<td><a href='excluirUsuario.php' class='btn_Excluir'><i class='glyphicon glyphicon-remove'></i></a></td>";
            echo "<td><a href='excluirUsuario.php' class='btn_Alterar'><i class='glyphicon glyphicon-pencil'></i></a></td>";
            echo "<td>$linha[0]</td>";
            echo "<td>$linha[1]</td>";
            echo "<td>$linha[2]</td>";
            echo "<td>$linha[3]</td>";
            echo "</tr>";
        }
        echo "</table>";
    }
    mysql_close($conn);
?>

excluiUsuario.php

<?php
     // incluindo o arquivo que faz a conexao com o banco
    include ("../includes/conexao.php");

    // Recebendo o valor enviado pelo link
    $COD_IDENT_USUAR = isset($_POST['COD_IDENT_USUAR']) ? $_POST['COD_IDENT_USUAR'] : '';

    mysql_query("DELETE FROM tbl_Usuarios WHERE COD_IDENT_USUAR ='".$COD_IDENT_USUAR."'");

    //fechando a conexao com o banco
    mysql_close($conn);

?>

Using these codes, I am therefore not deleting, it sends the delete pageUsuario.php but nothing happens.

  • var id = parent.attr('COD_IDENT_USUAR'); shouldn’t be pai instead of parent?

  • made the changes but still goes only to the page excluiUsuario.php, however it does not forward the id.

  • in PHP you are waiting to receive $_POST['COD_IDENT_USUAR'] but in JS you are sending data: "id=" +id,I think it should be data: {id: id}, in the JS and $_POST['id'] in PHP...

  • Notice: Undefined index: id in /opt/lampp/htdocs/Renan/jrassessoria/admin/paginas/excluirUsuario.php on line 6

  • Where the attribute element is in HTML COD_IDENT_USUAR?

  • It comes from my query: // executes query and stores the returned result in the $result variable $result = mysql_query("SELECT COD_IDENT_USUAR, TXT_NOMEX_USUAR, TXT_ENDER_EMAIL, FLG_STATU_USUAR, DAT_ULTIM_LOGIN from tbl_USUARIOS");

  • But where it is being inserted into HTML?

Show 2 more comments

2 answers

4


Change

<a href='excluirUsuario.php' id='btn_Alterar'><i class='glyphicon glyphicon-pencil'></i></a>

For

<a href='excluirUsuario.php' id='".$ID_DO_USER."' class='deleta'><i class='glyphicon glyphicon-pencil'></i></a>

Above you determine a class, because it will be multiple lines. And the user ID for each one in the LINK. This is just a Pseudo-Code. Adjust your way, put the ID variable correctly in the ID field="".

$(".deleta").click(function(e){
        e.preventDefault(); 
        var pai = $(this).closest('TR'); 
        var id = this.id; 
        $.ajax({ type: "POST", 
            data: "id=" +id, 
            url: "excluirUsuario.php", 
            success: function(msg){ $('#'+id).fadeOut(300); 
        } 
});

I didn’t even see your PHP.

  • 1

    Your code is error on line 49, which is: echo "<td><a href='excluirUsuario.php' id='". $COD_IDENT_USUAR."' class='deleta'><i class='glyphicon glyphicon-remove'></i></a></td>";

  • So that’s why I told you to put the variable correctly. Because I didn’t get into the HTML part of your code a lot. But now that I’ve seen just take out the double quotes and the dots surrounding the variable. So: id='$COD_IDENT_USUAR'

  • And also in your Select you must bring the name of the ID field. And put in While the same as you did for the other fields... Name...

  • It goes on the same way, making the mistake.

1

First, you have to put in your query the user ID, which by its delete code is COD_IDENT_USUAR:

 $resultado = mysql_query("SELECT TXT_NOMEX_USUAR, TXT_ENDER_EMAIL, FLG_STATU_USUAR, DAT_ULTIM_LOGIN, COD_IDENT_USUAR from tbl_USUARIOS");

Place the id read as data attribute on the line:

 while($linha = mysql_fetch_array($resultado))
 {
    echo "<tr data-id='$linha[4]'>";

There is a problem with the buttons you are inserting on the lines, you cannot use the same id for all. Instead, use a class:

 echo "<td><a href='excluirUsuario.php' class='btn_Excluir'><i class='glyphicon glyphicon-remove'></i></a></td>";
 echo "<td><a href='excluirUsuario.php' class='btn_Alterar'><i class='glyphicon glyphicon-pencil'></i></a></td>";

Finally, read the attribute to send the parameter to the exclusion script:

$("#elemento-pai-da-tabela").on('click', '.btn_Excluir', function(e){
        e.preventDefault(); 
        var $trPai = $(this).parent().parent(); 
        var id = $trPai.data('id'); 
        $.ajax({ type: "POST", 
            data: { 'COD_IDENT_USUAR': id }, 
            url: "excluirUsuario.php", 
            success: function(msg) { 
                $trPai.remove(); 
            } 
    }); 
}); 

As you dynamically created your elements, you will have to associate the click event in a parent element of them (in my example I used #elemento-pai-da-tabela, you did not show). I suggest leaving a fixed table and adding lines dynamically.

  • Continues with the same error: echo "<td><a href='excluirUsuario.php' id='$COD_IDENT_USUAR' class='deleta'><i class='glyphicon glyphicon-remove'></i></a></td>";

  • You’re using the solution of the other answer, try mine.

  • Still giving an error here: // Receiving the value sent by link $COD_IDENT_USUAR = $_POST['COD_IDENT_USUAR']; What is the correct way to receive a value ?

  • take a look again.

Browser other questions tagged

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