Update database with AJAX Switche button (Materialize)

1

I'm using the Materialize FrameWork, in it I have a switch (Switche) that switches between ON and OFF , just in html, I wanted to insert this into a database Mysql, all in real time, by pressing the button, it changes the value in the database, 0 for OFF for ON , when pressing the button, if no database is 0 change to 1, and see and versa, if in the database is 1, the button should remain on, ie symbolizing the ON ! (The button in the 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 on the real-time data pool?

    
asked by anonymous 24.12.2017 / 16:58

1 answer

1

You can submit form data to the server using api fetch ("native" ajax). The necessary code for this is this:

 <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>

A onchange event is added to the checkbox, and then the tagged or unselected value is created, created a formdata object, and then sent to the url server.php using api fetch.

Now the server can be done this way ( server.php file ):

<?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 reference to the mysqli_* functions refer to w3c .

    
24.12.2017 / 22:15