Button change the status

Asked

Viewed 1,941 times

2

I have a code where the customer clicking the button, it will activate or not a user, and of course, change the status in the database. So far everything ok. However, the code has two buttons, On and Off, and initially the Off button is hidden by default. See below:

$('button#btn-cancelar').hide();

So in PHP I did this way:

if($jmVagas->StatusVagas == 'A'){
  $botao = "$('button#btn-cancelar').hide();";
}if($jmVagas->StatusVagas == 'N'){
  $botao = "$('button#btn-salvar').hide();";
}

But when you click the button, it changes the status in the bank correctly, but the view appears the same in both. I will post the code for you:

Jquery:

<script type="text/javascript">
    $(document).ready(function(){
  //   $('button#btn-cancelar').hide();
  <?php
  echo $visualizarVagas[1];
  ?>

        $('button#btn-salvar').click(function(){
            $('button#btn-salvar').hide();
          $('button#btn-cancelar').show();
          var valor = $(this).attr('value');
           $('button#btn-cancelar').text("Desativado").attr({
              title:"Desativado"
        });
        jQuery.ajax({
          url : "alterar.php?v=N&k="+valor,
          dataType : 'json',
          async : false,
          success : function(msg) {
          }
        });
        });
        $('button#btn-cancelar').click(function(){
            $('button#btn-salvar').show();
        $('button#btn-cancelar').hide();
        var valor = $(this).attr('value');
            $('button#btn-salvar').text("Ativado").attr({
                title:"Ativado"
            });
        jQuery.ajax({
          url : "alterar.php?v=A&k="+valor,
          dataType : 'json',
          async : false,
          success : function(msg) {
          }
        });
        });
    });
    </script>

PHP:

while(...){

    if($jmVagas->StatusVagas == 'A'){
      $botao = "$('button#btn-cancelar').hide();";
    }if($jmVagas->StatusVagas == 'N'){
      $botao = "$('button#btn-salvar').hide();";
    }

         $listar .= "<button class=\"btn btn-xs btn-primary\" id=\"btn-salvar\" value=\"".$jmVagas->IdVagas."\" title=\"Ativado\">Ativado</button>";
         $listar .= "<button class=\"btn btn-xs btn-danger\" id=\"btn-cancelar\" value=\"".$jmVagas->IdVagas."\" title=\"Desativado\">Desativado</button>";
}
  • Why you do not work the IDE in ajax Success instead of putting the jquery command in a php variable ?

  • 1

    Hello Gabriel. Forgive me the ignorance, because I do not know very well ajax/jquery. How would do this exactly?

1 answer

1


// Array Json exemplo de retorno do php
var myArray = [{
  "nome": "Gabriel",
  "senha": "123",
  "ativo": "Ativado"
}, {
  "nome": "Rodrigues",
  "senha": "1234",
  "ativo": "Desativado"
}, {
  "nome": "Fonseca",
  "senha": "98745",
  "ativo": "Ativado"
}];

// carrega os usuarios na tabela
var table = '';
$.each(myArray, function(key, val) {
  table += '<tr>';
  table += '<td>' + myArray[key].nome + '</td>';
  table += '<td>' + myArray[key].senha + '</td>';
  // verifica se o usuario em questão esta ativado ou não criando um botão para aciona-lo
  if (myArray[key].ativo === "Ativado") {
    table += '<td><button class="btn btn-success" name=' + myArray[key].nome + '>' + myArray[key].ativo + '</button></td>';
  } else {
    table += '<td><button class="btn btn-default" name=' + myArray[key].nome + '>' + myArray[key].ativo + '</button></td>';
  }
  table += '</tr>';
});
// preenche os usuarios dinamicamente na tabela
$("tbody").append(table);

// no click do botao pegar o nome do usuario e a acao dele.
$("button").click(function() {
  var nomeUsuario = $(this).attr("name");
  var acao = $(this).text();
  console.log(nomeUsuario);
  console.log(acao);
  // se o usuario estiver ativo, desative ele, você precisa adicionar um ajax para enviar a acao para o php, pode ser um update where cliente = nomeUsuario.
  if (acao === "Ativado") {
    $(this).text("Desativado").removeClass("btn-success").addClass("btn-default");
  } else {
    $(this).text("Ativado").removeClass("btn-default").addClass("btn-success");
  }
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<table class="table">
  <thead>
    <tr>
      <th>Nome</th>
      <th>Senha</th>
      <th>Ativo</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>

The logic is there, you just need to adapt to your problem and put an ajax to change the status in the database.

  • Hello Gabriel. Right. Unfortunately it didn’t work. I believe that is why the buttons are inside while() of PHP. When I click on the second user, the first user button changes as the second.

  • The idea I had was this: The buttons come inside while() of PHP. Soon the buttons will have the same names (id="btn-save"). Couldn’t jquery create an array and put in this code tb? ( $('button#btn-save'). Hide(); )

  • Jose, wouldn’t it be good practice to use the same id for all, recommend you differentiate by attribute name=, if you see the test above, each button is named after the user you want to enable/disable

  • Hello Gabriel. Sorry for the delay. I will be making tests and return as soon as I finish.

  • 1

    Thanks Gabriel. It worked!!!

Browser other questions tagged

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