Toggle update Mysql database automatically

Asked

Viewed 115 times

0

How can I make through toggle I update my database? I have toggle below:

inserir a descrição da imagem aqui

For that, I’m doing it this way:

<div class="onoff">
  <strong>Desabilitar notificações por e-mail:</strong>
  <input type="checkbox" class="toggle" id="onoff">
  <label for="onoff"></label>
  <input type="hidden" name="Avisar" id="campo1" value="0">
</div>

......

<script type='text/javascript'>
//<![CDATA[
window.onload=function(){
var onoff = document.getElementById('onoff');
onoff.addEventListener('change', function() {
    estado = this.checked ? 'S' : 'N';
    var campo = document.getElementById("campo1").value = estado;
    $.ajax({
        url: 'notificacoes.php',
        type: 'post',
       data: {
           estado: this.checked,
           campo: campo
       }       
   }).done(function(msg) {
   });
});
}//]]>
///////////////////
</script>

And PHP:

....
$idUsuarios = $_SESSION["IdUsuarios"];
$status = $_POST["estado"];
....
mysqli_query($this->conexao,"UPDATE tabela SET Notificacoes = '".$status."' WHERE IdUsuario = '".$idUsuarios."';

Only it’s not updating. The problem is in Jquery, for the PHP is working properly.

  • Have you tried passing the date as a string? Ex.: date: "status="+this.checked+"&field="+field

  • You used a var_dump in php or an Alert on javascript to know if the request is being called when toggle is modified?

  • tries to place an Alert in addeventlistener to see if it is being called.

  • Hello guys. About passing as string, I did and did not pass the values. I gave an Alert as requested and the value (S or N) is coming correctly. We isolated PHP and ran a test directly on it and it’s working, so we ruled out that the problem is in PHP.

  • The desired value arrives in php?

  • Yes... what I’m finding strange is that even the values being "S" and "N" when I echo the variable $status and a console.log(data), it returns me "TRUE" or "FALSE" and not "S" or "N". When I use a ternary in PHP, it returns only TRUE.

  • When I give console.log(status), it usually appears S or N.

  • It’s like the value isn’t actually going to PHP.

Show 3 more comments

1 answer

1


I didn’t quite understand the difference between state and field, but I believe that field will pass which field you want to enable or disable notifications and the status is yes and no.

If this is the case, I suggest changing:

var campo = document.getElementById("campo1").value = estado;

for:

var campo = document.getElementById("campo1").value;

because field1 was changing its value when changing the state. (If this should occur ignore this part)

After you defined the state as S or N but pulled again the this checked.

estado: this.checked,

When it should be:

estado: estado

I hope it helps you!

  • You’ve helped Henry a lot. Thank you very much!

Browser other questions tagged

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