By clicking a php run button

Asked

Viewed 1,214 times

4

Is it possible for me to merge the php with the jQuery? For example, when you clicked on a button you picked up an input value via jQuery and move on to php, an example of what I’d like to do:

$('btn').on('click', function(){
<?php
// ID de exemplo
$id = 1;
// Selecionando nome da foto do usuário
$sql = mysql_query("SELECT foto FROM usuarios WHERE id = '".$id."'");
$usuario = mysql_fetch_object($sql);
// Removendo usuário do banco de dados
$sql = mysql_query("DELETE FROM usuarios WHERE id = '".$id."'");
// Removendo imagem da pasta fotos/
unlink("fotos/".$usuario->foto."");
?>});

Would it be possible?

1 answer

5


It’s possible, but not like that. You have to create an ajax function and call another PHP script when the button is clicked, the way you made the PHP code always runs when the page is visited, no matter if the click event runs.

A simple example:

$('btn').on('click', function() {
    $.ajax({
        url: "/script.php",
        data: { id: 1 }
    }).done(function() {
       alert('Script executado.');
    })
});

More information about $.ajax().

php script.

<?php
$id = (int) $_GET['id'];
// Selecionando nome da foto do usuário
$sql = mysql_query("SELECT foto FROM usuarios WHERE id = " .$id);
$usuario = mysql_fetch_object($sql);
// Removendo usuário do banco de dados
$sql = mysql_query("DELETE FROM usuarios WHERE id = " . $id);
// Removendo imagem da pasta fotos/
unlink("fotos/".$usuario->foto."");

No more functions starting with mysql_, more information.

Browser other questions tagged

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