Confirm SQL Delete using Javascript Confirm [closed]

0

Even if you click the cancel option it will delete. Can you help me? This is my code:

if (($page == 'delete') && $id > 0) {

    echo '<script>

             var r = confirm("Deseja realmente excluir esse usuário?");

             if(r != true){ return false; }else{
                 return true;
                '; 
    // executa o SQL para excluir
    $sql = $conn->prepare('DELETE FROM registro.cadastro WHERE id= :id');

// prepara os dados
    $data = array(':id' => $id);

    try {
        // executa o SQL
        $sql->execute($data);

// Mostra a mensagem de erro
        $mensagem = alert('Registro deletado.');
    } catch (PDOException $e) {

        // mostra a mensagem
        $e->getMessage();
    }
    echo'}
    </script>';
}
    
asked by anonymous 12.06.2016 / 22:11

1 answer

1

Example with jQuery

In the official site download the jQuery library and add it to head :

<script src="js/jquery-1.12.2.min.js"></script>

Call the function below, replace the URL with that of your PHP file:

function deleta(){
    $(document).ready(function(){
        var sim = confirm("Deletar?");
        if (sim){
            var url = "retorno.json";
            $.getJSON(url, function(json) {
                if (json.status == "OK")
                    alert("Deletado!");
                else
                    console.log(json);
            });
        }
    });
}

Your PHP file named in the URL above will make the operation in the database, if it is something specific you can use Ajax and a form and send parameters to post . Remember to return a json by php:

{"status":"OK", "msg":"Sucesso!"}

To do this, simply print this on the screen. Do not print anything on the screen other than this:

echo '{"status":"OK", "msg":"Sucesso!"}';

If all goes well in delete prints this above, otherwise, with status "error" instead of "OK".

I hope to help.

    
13.06.2016 / 11:51