First of all I want to say that this line in the block else
</script>";
is wrong and would cause a misinterpretation in the code. You had to have the quotation mark before the first byte '<'
: "</script>"
, and anyway it would cause an interpretation error since there is no statement that needs a string (if it was in JavaScript, would be different, "</script>"
would be returned in the console, or if it was equal to "use strict"
would go to strict mode, or ignored; edit : in PHP the string is ignored). Use echo
to play a string in HTML.
I understand that you want to display a confirmation box to delete something in the database. In this example I will show the confirm
JavaScript function.
confirm
is global, that is, it is located in object window
. When calling this function -_- the page is locked while the user does not confirm (does not respond) the confirmation box that was opened with the confirm
function itself, and once it is confirmed it returns true
if the user response was "Yes", or false
if the answer was "Cancel", or something like that. Then with this function we can make a condition type 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 reply "yes" to the confirmation box and to have something removed from a database table. You can not do this directly from JavaScript, so you'll have to use AJAX, which will run the file beside the server (the * .php file). It will greatly magnify the answer if I explain about it, but I leave the question answered link 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 it within 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 -. -, there is in fact the method POST
plus GET
. I'm not going to explain that much because the question is a bit 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
}