Deleting records marked with checkbox

Asked

Viewed 580 times

2

I wish I could delete multiple records from a table just by selecting the records using the checkbox, Like Gmail, I select the emails I want to delete or mark as read. Because when I need to delete some record I still have to keep deleting one at a time.

I’m very lay in JS, until I was able to show in an Alert the array with the ids that the user selected, but I don’t know how to execute an sql statement to delete the marked records, the idea would be to delete as soon as the user click "OK" inside the Alert.

I’ve been searching on the Internet but I still had doubts, some examples used ajax.

Sample code

<script type="text/javascript">
    function coletaDados() {
        var ids = document.getElementsByClassName('editar');
        coletaIDs(ids);
    }

    function coletaIDs(dados) {
        var array_dados = dados;
        var newArray = [];
        for (var x = 0; x <= array_dados.length; x++) {
            if (typeof array_dados[x] == 'object') {
                if (array_dados[x].checked) {
                    newArray.push(array_dados[x].id)
                }
            }
        }
        if (newArray.length <= 0) {
            alert("Selecione um pelo menos 1 item!");
        } else {
            alert("Clique em OK para confirmar a exlusão do(s) registro(s) : [ " + newArray + " ]");
        }
    }
</script>

<?php
// Variáveis declaradas somente para ilustrar o exemplo

$id1 = "1";
$id2 = "2";
$id3 = "3";
?>

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Tabela de Exemplo</title>
    </head>
    <body>
        <table border="1" width="10%">
            <tr>
                <td>Registros</td>
            </tr>
            <tr>
                <td><input type="checkbox" class="editar" id="<?php echo "$id1"; ?>"> A</td>
            </tr>
            <tr>
                <td><input type="checkbox" class="editar" id="<?php echo "$id2"; ?>"> B</td>
            </tr>
            <tr>
                <td><input type="checkbox" class="editar" id="<?php echo "$id3"; ?>"> C</td>
            </tr>
            <tr>
                <td colspan="2"><button onclick="coletaDados()" class="btn btn-primary" style="width:100%">Excluir</button></td>
            </tr>
        </table>
    </body>
</html>
  • You want to delete without loading the page or sending a form that loads the page?

  • Want to delete without loading page

  • No reload is required Ajax, and a php page specifies to interpret the Ajax request and delete the data

  • and if it were to send to another page? something without ajax

1 answer

1


This code sends by ajax the id’s that you want to delete:

View comments

function coletaDados() {
    var ids = document.getElementsByClassName('editar');
    coletaIDs(ids);
}

function coletaIDs(dados) {
    var array_dados = dados;
    var newArray = [];
    for (var x = 0; x <= array_dados.length; x++) {
        if (typeof array_dados[x] == 'object') {
            if (array_dados[x].checked) {
                newArray.push(array_dados[x].id)
            }
        }
    }
    if (newArray.length <= 0) {
        alert("Selecione um pelo menos 1 item!");
    } else {
      var ajax = new XMLHttpRequest();

      ajax.open("POST", "nomeDaPagina.php", true); //definir o nome do arquivo que recebe os dados via POST.
      ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");


      ajax.send('ids=' + newArray);

      ajax.onreadystatechange = function() {

        if (ajax.readyState == 4 && ajax.status == 200) {

          var data = ajax.responseText;
          // seu código para apagar os ids da página
          alert(data); // retorno da página PHP.
        }
      }
    }
}

The PHP page that will process the ID’s to delete the records must be waiting for the parameter ids by the POST method as below:

$ids = $_POST['ids'];

If you are using PDO you can delete this way:

$ids = $_POST['ids'];
require_once('db.php'); //chama seu arquivo de conexão com o banco de dados

$exclui = $con->prepare("DELETE FROM suaTabela WHERE id in ( :ids )");
$exclui->bindValue(":ids", $ids);
$exclui->execute();
echo "ID's apagados: ". $ids; //retorno que será enviado para o alert.
  • 1

    That’s exactly what it was!

Browser other questions tagged

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