Update database with AJAX Switche button (Materialize)

Asked

Viewed 97 times

1

I’m using the Materialize Framework, in it I have a button (Switche) that switches between ON and OFF, just in html, I wanted to insert this into a Mysql database, all in real time, by pressing the button, it changes the value in the database, 0 to OFF and 1 to ON, when pressing the button, if in the database is 0 change to 1, and see and versa, if in the databank is 1, the button must remain on, that is, symbolizing the ON! (The button in materialize I a checkbox, checked should be equal to ON)

HTML:

  <div class="switch">
    <label>
      Off
      <input type="checkbox">
      <span class="lever"></span>
      On
    </label>
  </div>

In PHP I thought of something like this:

$valor = $_POST['Switche'];

if($valor == 1){
    $valor = 0;
}else{
    $valor = 1;
}

How can I do this and update in real-time data stream ?

1 answer

1


You can send the form data to the server using the fetch api ("native" ajax). That’s the code for it:

 <div class="switch">

    <label>
      Off
      <input type="checkbox" id="escolha">
      <span class="lever"></span>
      On
    </label>
</div>

<script>
    var escolha = document.getElementById('escolha');
    escolha.addEventListener('change', function(){
        atualizarSwitch();  
    });

    function atualizarSwitch(){
        var escolha = document.getElementById('escolha');
        var formulario = new FormData();

        var escolha_estado = 0;

        if(escolha.checked === true){
            escolha_estado = 1; 
        }

        formulario.append('switch', escolha_estado);

        fetch("servidor.php", {
            method: "POST",
            body: formulario
        }).then(function(resposta) {
            return resposta.text();
        }).then(function(resposta) {
            alert(resposta);
        }); 
    }
</script>

Basicamnete is added an event onchange for the checkbox, and then captured the marked or unmarked value, created an object formdata, and then sent to the url php server. using the fetch api.

Already the server can be done like this (file php server.):

<?php 
$valor = $_POST['switch'];

if($valor == 1){
    $valor = 0;
}else{
    $valor = 1;
}

echo $valor;

//quando construir a função chame descomente a linha abaixo
//salvarNoBanco($valor);

function salvarNoBanco($valor){
    $conexao = mysqli_connect('host', 'usuario', 'senha', 'nome_banco');
    $status = mysqli_query($conexao, 'UPDATE nome_tabela SET algum_campo = ' . $valor . ' WHERE algum_campo = alguma_valor_condicao');
    return $status;
}

For a review of the mysqli_* see at w3c.

  • What if I wanted multiple checkboxs? Just out of curiosity, I’m not the author of the question.

Browser other questions tagged

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