First of all I want to say that this line in the block of else
</script>";
is wrong and would cause an interpretation error in the code. You had to have put the quote before the first byte '<'
: "</script>"
, and would otherwise cause an interpretation error since there is no statement that needs a string (if it were in Javascript, it would be different, "</script>"
would be returned on the console, or if it were equal to "use strict"
would go the strict way, or ignored; Edit: in PHP the string is ignored). Use echo
to play a string in HTML.
I understood that you want to display a confirmation box to delete something in the database. In this example I will show the function confirm
javascript.
confirm
is global, ie is located in the object window
. When calling this function -_- the page is locked while the user does not confirm (does not reply) the confirmation box that was opened with the function itself confirm
, and once confirmed returns true
whether the user’s response was "Yes", or false
if the answer was "Cancel", or something like that. Then with this function we can make a condition like if(confirm("Quer me responder?")) alert("Então você quer me responder"); else confirm(":(");
, or confirm("Quer me responder?") && alert("Uau! Você é incrível! :D Herói!")
.
The goal is for the user to answer "yes" to the confirmation box and for something to be removed from a database table. You cannot do this directly from Javascript, so you will have to use AJAX, which will run the file next to the server (the *.php file). It will greatly amplify the answer if I explain about it, but I leave the link of a question answered that will help you.
And another thing, I see no point in using PHP to build the HTML page and run Javascript. To answer your question, try putting this inside your else
.
echo '<script>
if(confirm("Deseja remover o *?")) {
var xhr = new XMLHttpRequest;
xhr.get("GET", "delete.php?id='. $id .'", true);
xhr.onreadystatechange = function() {
if(this.readyState === 4) {
if(this.status === 200) {
alert("Deletado.");
}else{
/* Erro ao requisicionar o arquivo *.php */
}
}
};
xhr.send();
}
</script>';
And the delete.php file should have an id specified in the URL -. -, actually there is the method POST
besides the GET
. I’m not going to explain that much because the question is a little broad, but let’s see if you understand:
<?php
// se o id foi declarado no URL, e.g: *url*/?id=num
if(isset($_GET['id'])) {
// pega e converte o id no url para número (caso vier como uma string, mas impossível de acontecer, eu creio)
$id = intval($_GET['id']);
// obs: isso é inseguro se você não
//detectar o usuário que está deletando algo do db
// remova algo do db usando $id
}
You want the user to confirm to delete something in the database through the block
else
?– Klaider