Pass array of a checkbox as parameter

1

I'm developing in PHP a basic system, and on the home screen I'm listing all registered users. For each user, I have a checkbox that gets the value of the user code. I would like to check if the checkbox is correct and how would I go about sending the array to another page that performs, for example, deleting the selected users? This through the click of a button ...

//Botões
<div class="span4" style="margin-left: 0;width:470px;text-align: right;">
            <a href="cadastroUsuario.php"><button class="btn btn-danger" type="button">Novo Usuário</button></a>
            <div class="btn-group">
              <a class="btn btn-inverse"><i class="icon-th-list icon-white"></i> Opções</a>
              <a class="btn btn-danger dropdown-toggle" data-toggle="dropdown" ><span class="caret"></span></a>
              <ul class="dropdown-menu" style="text-align: left;">
                <li><a href="#"><i class="icon-eye-open"></i> Visualizar Tudo</a></li>
                <li><a href="#"><i class="icon-pencil"></i> Editar Usuário</a></li>
                <li><a href="#"><i class="icon-trash"></i> Apagar Usuário</a></li>
                <li class="divider"></li>
                <li><a href="#"><i class="icon-check"></i> Ativar Usuário</a></li>
                <li><a href="#"><i class="icon-ban-circle"></i> Desativar Usuário</a></li>
              </ul>
            </div>
        </div>

//Tabela com os dados dos usuários
<table width="100%" border="0" class="table table-striped table-hover table-bordered">
              <tr>
                <th nowrap="nowrap">#</th>
                <th nowrap="nowrap">Codigo</th>
                <th nowrap="nowrap">Empresa</th>
                <th nowrap="nowrap">Cidade</th>
                <th nowrap="nowrap">UF</th>
                <th nowrap="nowrap">Telefone</th>
                <th nowrap="nowrap">CPF/CPNJ</th>
                <th nowrap="nowrap">E-Mail</th>
                <th nowrap="nowrap">Status</th>
                <th colspan="2" nowrap="nowrap">Ações</th>
              </tr>
            <?php
                if ($resultadoBusca != null){

                    foreach($resultadoBusca as $escrever){
//checkbox recebedo cod_user                            
echo "<tr><td><input type=checkbox name=\"check_idUser[]\" value=\"".$escrever['cod_user']."\"></td>
                        <td>" . $escrever['cod_votoran'] . "</td>
                        <td>" . utf8_encode($escrever['empresa_user']) . "</td>
                        <td>" . utf8_encode($escrever['cidade_user']) . "</td>
                        <td>" . $escrever['estado_user'] . "</td>
                        <td>" . $escrever['fone_user'] . "</td>
                        <td>" . $escrever['cpfcnpj_user'] . "</td>
                        <td>" . $escrever['email_user'] . "</td>
                        <td>" . $escrever['status_user'] . "</td>
                        <td>";
                        echo "<a href=\"visualizarUsuario.php?cod=".$escrever['cod_user']."\"><i class=\"icon-eye-open\" title=\"Visualizar Todos os Dados do  Usuário!\"></i></a>";
                        if($escrever['status_user']=='ativo'|| $escrever['status_user']=='Ativo')
                        {
                            echo "<a href=\"desativarUsuario.php?cod=".$escrever['cod_user']."\"> <i class=\"icon-ban-circle\" title=\"Desativar Usuário!\"></i></a>";
                        }else{
                            echo "<a href=\"ativarUsuario.php?cod=".$escrever['cod_user']."\"> <i class=\"icon-check\" title=\"Ativar Usuário!\"></i></a>";
                        }
                        echo "<a href=\"editarUsuario.php?cod=".$escrever['cod_user']."\"> <i class=\"icon-edit\" title=\"Editar Usuário!\"></i></a>";
                        echo "<a href=\"excluirUsuario.php?cod=".$escrever['cod_user']."\"> <i class=\"icon-remove\" title=\"Remover Usuário!\"></i></a></td>
                                            </tr>";
                    }  
                                        }else{
                    echo '<table style="width:100%; background: none repeat scroll 0% 0% rgb(242, 222, 222);"><div align="center"><strong><tr><td>Desculpe! Não Existe Nenhum Usuário Cadastrado</td></tr></strong></div></table>';
                }
            echo "</table>";
            ?>

    
asked by anonymous 31.10.2014 / 10:47

1 answer

2

Dividing the problem into parts the steps you have to do are:

  • Create an event handler to start an action when you click "Erase All"
  • Check which users are chosen to be removed
  • Send to PHP via AJAX and when confirmation comes, then delete in HTML
  • Delete in database (server side / PHP)
  • Delete users (back to client side / JavaScript)
  • Now by steps:

    # 1

    $('i.icon-trash').closest('li').click(fnApagar);
    

    This code will look for a li that has in i.icon-trash and call the function fnApagar() when this li is clicked.

    # 2

    Here you have to look in the table which users are chosen. It would be nice if this table had an ID so there would be no confusion if there is more than one table on the page.

    var paraRemover = $('table tr input:checkbox:checked').map(function(){ 
        return {
            cod_votoran: this.value, 
            tr: $(this).closest('tr')[0]
        }
    }); 
    

    In this line of code above I will search the chosen users and save 2 things. The code I need for the database, and the table line to later delete.

    # 3

    Ajax! Ajax is the way the browser has to communicate with the server and send and receive data without having to load the entire page again.

    $.ajax({
        url: "endereco.php",
        type: 'post',
        data: {codigos: [array com os códigos a remover]},
        success: function(resposta){
          // esta função é corrida quando a resposta volta do servidor
          // if (resposta == true) apagar esse(s) usuário(s)
        }
    });
    

    # 4

    Data sent to the server can be captured by $_POST . There you have to go through this array and do the removal in the database. In detail I can not answer because there is information in the question (you can ask a new question if you get caught up here).

    Example:

    $usuarios_a_apagar = $_POST['codigos'];
    $sql = implode(', ', $usuarios_a_apagar ); // para ficar com "cod1, cod2, etc"
    

    Then in the query to the database you can use:

    "DELETE FROM clientes WHERE ID IN ($sql)"
    

    Then just send back to the client side the confirmation:

        if ($excluir == 2) echo '[true, "Usuário Excluí­do com Sucesso"]';
        elseif ($excluir == 0) echo '[false, "Houve um erro ao excluir usuário, talvez já tenha sido excluí­do anteriormente!"]';
        else echo '[false, "O Sistema apresentou algum erro, fale com o administrador!"]';
    

    # 5

    With the server response (assuming it returns true ) then we have to delete those table rows. Since we had already saved them we can do this:

    paraRemover.each(function(){ this.tr.remove(); });
    

    The complete (JS) code:

    $('i.icon-trash').closest('li').click(fnApagar);
    
    function fnApagar() {
        var paraRemover = $('table tr input:checkbox:checked').map(function () {
            return {
                cod_votoran: this.value,
                tr: $(this).closest('tr')[0]
            }
        });
    
        $.ajax({
            url: "endereco.php",
            type: 'post',
            data: {
                codigos: paraRemover.map(function(){ return this.cod_votoran; }).get()
            },
            success: function (resposta) {
                 if (resposta[0]) paraRemover.each(function(){
                    this.tr.remove();
                }); 
                alert(resposta[1]);
            }
        });
    }
    
        
    31.10.2014 / 12:07