Checkbox with id in name

Asked

Viewed 154 times

2

I would like to have a checkbox button on the site to enable and disable some action, I am using ajax to make the change immediately, the action would not need an F5 to work. The problem is that I am passing the id of the div created by php by the name of the check and it does not seem to be working because php does not change the value of check to 1 in the database. I would like to change its value from 1 - 0

<?
php
session_start();
include_once("conexao.php");

    $ativado = $_POST['ativado'];
    $nome = $_POST['nome'];

        $sql="UPDATE produto SET ID=$nome WHERE ativado='$ativado'";
        $query = mysqli_query($conn, $sql);

       echo $ativado;

     ?>
   <div class='col-3'>
              <label class='switch mt-3'>
                 <input class='input-check'type='checkbox' name='check".$row_produto['ID']."' value='0'>
                 <span class='check round'></span>
                </label>
                <button type='button'  class='close deletar mt-2'  id='".$row_produto['ID']." aria-label='Close'>
 <i class='fas fa-trash-alt'></i>
</button>
    </div>

$(document).ready(function () {
    $('input[type="checkbox"]').click(function () {
        var ativado = $(this).attr('value');
        var nome = $(this).attr('name');
        if ($(this).prop("checked") == true) {
            $('input[name=' + nome + ']').val('0');
            alert("Checkbox is checked. " + nome + "valor= " + ativado);
            $.ajax({
                type: 'POST',
                url: '../php/ativo_produto.php',
                data: {
                    ativado: ativado,
                    nome: name,
                },
                success: function (response) {
                    alert(response);
                }
            })

        } else if ($(this).prop("checked") == false) {
            $('input[name=' + nome + ']').val('1');
            alert("Checkbox is checked. " + nome + "valor= " + ativado);
            $.ajax({
                type: 'POST',
                url: '../php/ativo_produto.php',
                data: {
                    ativado: ativado,
                    nome: name,
                },
                success: function (response) {
                    alert(response);
                }
            })
        }
    });
});

  • When checked the value of the checkbox is 0, and when it’s not there the value is 1? Wouldn’t it be the other way around?

  • I changed it unintentionally. But anyway it doesn’t even get called or changed in the bank

  • What do you mean it’s not even called? It doesn’t give the Alert? It has several problems

  • it is not changed, because the value that is there is 0 and wanted to change to 1

2 answers

1


One mistake is that you’re going through name in the variable nome in the data from AJAX. The right thing would be nome: nome, and not nome: name.

But how do you want to pass one id, which would be a number, put an attribute data-id at checkbox with the id from PHP and send this value in AJAX.

Missing also close attribute id of button with single quotes:

id='".$row_produto['ID']."'
                          ↑

Put in the checkbox:

<input class='input-check'type='checkbox' data-id='".$row_produto['ID']."' name='check".$row_produto['ID']."' data-id="1" value='0'>
                                             ↑↑↑

You can do it in a simpler way. No need to use a if to repeat the same AJAX code. With only one AJAX code you can send the values correctly (0 or 1) in the variable ativado and its id. The use of this is useful in these cases because it references the object that triggered the event.

See how simple the code is:

$(document).ready(function () {
   $('input[type="checkbox"]').click(function () {
      var nome = this.name; // pega o name o checkbox clicado
      this.value = this.checked ? '1' : '0'; // muda o value para '1' se tiver checado, e '0' deschecado
      var ativado = this.value; // pega o valor do checkbox
      var id = $(this).data("id"); // pega o id no data-id

      alert("Checkbox is checked. " + nome + "valor= " + ativado);
      $.ajax({
         type: 'POST',
         url: '../php/ativo_produto.php',
         data: {
            ativado: ativado,
            id: id,
         },
         success: function (response) {
            alert(response);
         }
      });
   });
});

And in PHP change the POST $name for:

$id = $_POST['id'];

And in SQL:

$sql="UPDATE produto SET ID='$id' WHERE ativado='$ativado'";
  • I tested but still does not seem to solve, it really changes in html, can see with inspecting but not enough to send to the bank ... the value does not go to the bank at all. ah yes, when I ask for an echo in php to see what value it is sending, it sends the of value but never appears the of id in echo, it is empty

  • I tested it here and it worked right. See if you did everything right as you explain the answer.

  • Could it be because I’m putting in the bank ID? pq I’m not creating it as html, it’s being created dynamically as a php and called pro html

  • Would not be: "UPDATE produto SET ativado='$ativado' WHERE ID='$id'"?

  • Thank you very much from my heart, it’s been a long time since I’ve been standing on this and I didn’t know why, I was already getting discouraged because it’s not such a complex thing and I was already hammering here

1

You are setting ativadowith the attribute value, which is set to "0". It should receive the value of 0 or 1 depending on the checked. The if and Else blocks also do not need to contain all the code, only need to put there if it will send 0 or 1; or still use the operator Ternary to be more succinct.

<div>
<input type='checkbox' name='checkProd1' data-id='Prod1'>
  <label for="checkProd1">prod 1</label><br />
  <input type='checkbox' name='checkProd2' data-id='Prod2'>
  <label for="checkProd2">prod 2</label><br />
  <input type='checkbox' name='checkProd3' data-id='Prod3'>
  <label for="checkProd2">prod 3</label><br />
 </div>

$(document).ready(function () {
    $('input[type="checkbox"]').click(function () {
        var ativado = $(this).prop('checked') ? 1 : 0;
        var id = $(this).attr('data-id');
        alert("Checkbox " + id + " ativado? " + ativado);
      /* $.ajax({
                type: 'POST',
                url: '../php/ativo_produto.php',
                data: {
                    ativado: ativado,
                    id: id,
                },
                success: function (response) {
                    alert(response);
                }
       })*/
    });
});

See this example worked here: https://playcode.io/324057?tabs=console&script.js&output

Browser other questions tagged

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