Pass array of a checkbox as parameter

Asked

Viewed 640 times

1

I am developing in PHP a basic system, and on the home screen I am listing all registered users. For each user, I have a checkbox that receives the value of the user code. I would like you to check if the checkbox is correct and how would I send the array to another page that performs, for example, the deletion of selected users? This by clicking 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>";
            ?>

Tabela com usuários sendo listada na página

  • You’ll have to use AJAX... you know how to do?

  • I don’t know. I’m starting to develop in PHP and it’s one of my first experiences s;

  • Ok. Want to use pure Javascript or a library like Mootools or jQuery?

  • Dude, I have no idea, because I’ve never used any of these that you guys are talking about ;

  • Not knowing this makes it difficult to answer... another question: when this checkbox is clicked, whatever happens`stays on the same page but this user disappears, is it kind of transparent, or other? Has a database already with users?

  • Yes, I have a mounted base. And on the home screen through this table are being listed all users. Next to each one is placed this checkbox, but it does nothing but receive the value of cod_user. If you click on it nothing happens. And I actually ask here, why do people always help and believe that someone should have a north to help me.

  • Rodrigo I’ll give you an answer. You can answer the previous question/comment first: when this checkbox is clicked whatever happens?

  • By the introduction of the question @Sergio, he wants to use the checkbox mark one or more users and click on a make one post to a file where these users will be removed from the system. In terms of UI, they should be successfully removed from the list. :) (but this is my interpretation of the intended)

  • Nothing happens yet, as I had already said. I edited the post and put an image of the page to check how it is.

  • Rodrigo my question is more of a: what is your desire for me to answer how to do...

  • @Zuul because, hence my question above, "This user disappears, is it kind of transparent, or other?" to fine tune the answer :) (Oh, I just saw the image in the answer, it got better)

  • I want the following: As well as in the image, select the users I wish to delete, and click the highlighted 'DELETE USER' button to remove all selected users. As far as I searched, I would have to save in an array the selected values (I don’t know how) and after sending to a specific page that takes the array and makes the SQL to remove them from the BD.

  • Rodrigo can put here the HTML of this menu where you click "Delete User"?

  • I edited in the code, it’s the first part of it. Take a look.

Show 9 more comments

1 answer

2


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

  1. Create an Event Handler to start an action when pressing "Delete All"
  2. Check which users are chosen to be removed
  3. Send to PHP via AJAX and when confirmation comes, then delete in HTML
  4. Delete in database (server side / PHP)
  5. Delete users (back next to client / Javascript)

Now by steps:

#1

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

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

#2

Here you have to search in the table which users have chosen. It would be nice if this table had an ID so there is 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 look for the chosen users and save 2 things. The code I need for the database, and the table row for later deletion.

#3

Ajax! Ajax is the way the browser has to communicate with the server and send and receive data without having to load the whole 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. Then you have to go through this array and do the removal in the database. In detail I can not answer because fata information in the question (you can ask a new question if you get stuck here).

Example:

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

Then in the database query you can use:

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

Then all that remains is to 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 these lines from the table. As we had already saved them we can do so:

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

The complete code (JS):

$('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]);
        }
    });
}
  • I have another question related to everything we did here. I am doing the same thing now to activate multiple users. Everything already working. My only question is this: where do I have this.tr[0].remove(); it removes the table row, however, when active a user would like only to change the field Status for: Inativo and color Vermelho. Would have as?

  • @Rodrigosegatto can do that with classes. Like this.tr[0].classList.add('inativo'); or with jQuery $(this.tr[0]).addClass('inativo');

  • Testing right here [http://jsfiddle.net/ya1ytv3k/ ] tried both ways and nothing happens

  • @Rodrigosegatto an example to mark the red line: http://jsfiddle.net/ya1ytv3k/7/ don’t forget the CSS class. Ask new question if you have problem that we will help.

  • Not quite. But I’ll ask another question. : D

Browser other questions tagged

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