When clicking a button execute a php

4

Is it possible to merge php with jQuery ? For example, when I clicked on a button I would take the value of an input 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?

    
asked by anonymous 22.12.2015 / 02:43

1 answer

5

It is possible, but not this way. You have to create an ajax function and call another PHP script when the button is clicked, the way you did the PHP code is always executed when the page is visited, regardless of whether the click event is executed.

A simple example:

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

More information about $ .ajax () .

script.php

<?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."");

Do not use more functions that start with mysql_, more information .

    
22.12.2015 / 02:59