Confirm SQL Delete using Javascript confirm

Asked

Viewed 417 times

0

Even by clicking on the option cancel it does 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>';
}
  • Hi Danilo. I think you’re mixing PHP and Javascript. Do you know the difference between "client side" and "server side"? Take a look here: http://answall.com/q/608/129

  • someone knows a way this making this validation?

  • Did you see the link I suggested? Do you understand the question and answers? (I ask so we can help you )

  • First, following the previous comment, I advise checking using Javascript, and make a call to PHP sending the parameters to delete after this. Second, logical. Use parentheses like this: if ( ($page == 'delete') && ($id > 0) ) { ... }

1 answer

1

Example with jQuery

In the official website download jQuery library and add to head:

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

Call the function below, replace the URL with 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 called in the URL above will do the operation in the database, if it is something specific you can use Ajax and a form and send parameters by post. Remember to return a json by php:

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

To do this, just print it on the screen. Don’t print anything on the screen other than this:

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

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

I hope to help.

Browser other questions tagged

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