execute a function when clicked on the button

Asked

Viewed 1,112 times

0

I’m trying to make it only send to the database when you click the put button every time the page is loaded even if you don’t click 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 have any way to connect to the database via javascript and be safe I am happy to know also

1 answer

1


Unable to 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);
    });
});

No php (arquivo_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());
?>

Observing: the tag <button> by default is of type submit, that is, when clicked inside a form the page will be submitted, so that this does not occur set its type as button

<button type="button">Enviar</button>

Browser other questions tagged

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