perform a function when the button is clicked

0

I'm trying to make it just send to the database when I click the button however every time the page is loaded it sends even not clicking the button. This is the code I'm using

<script>
 var text = "foi clicado"
</script>
<button onclick="myFunction()">Click me</button>
<script>
function myFunction() {
    document.getElementById("d").innerHTML = "<?php 
        include 'conect.php';
        $ts = "<script>document.write(text)</script>";
        $TS2= $ts;
        $sql ="INSERT INTO 'ss'('nome') VALUES ('$TS2')";
        $query = mysqli_query($link, $sql) or die(mysqli_error());
        ?>";
}
</script>

If you can connect to the database via javascript and be safe, I'm happy to hear it too.

    
asked by anonymous 22.04.2018 / 16:53

1 answer

1

Can not run php code on the client side, you should use AJAX for this:

In JavaScript (JQuery):

$('#input').on('click', function(){
    $.ajax({
        //Para aonde vai a requisição (um outro arquivo)
        url: 'arquivo_php.php',
        //Os dados que devem ser passados (adicione um id ao input e coloque no lugar de #input)
        data: {ts: $('#input').val()},
        //Como vai ser passados os dados (o mesmo method do form)
        method: 'POST',
    }).done(function(data) {
        //Quando finalizar a requisição com sucesso
        alert('Concluído com êxito');
    }).fail(function(error) {
        //Quando finalizar a requisição com falha
        alert('Erro: ' + error);
    });
});

In php (php.php):

<?php 
    include 'conect.php';
    //Dado passado por post pelo ajax
    $TS2= $POST["ts"];
    $sql ="INSERT INTO 'ss'('nome') VALUES ('$TS2')";
    $query = mysqli_query($link, $sql) or die(mysqli_error());
?>

Note: The <button> tag by default is of type submit , ie when clicked inside a form the page will be submitted, so that it does not occur define your type as button

<button type="button">Enviar</button>
    
22.04.2018 / 17:28