This question already has an answer here:
I want to ask the user if he wants to delete a line from the database, so I proceed like this :
<script>
function show_confirm() {
var x;
if (confirm("Press a button!") == true) {
x = "You pressed OK!";
} else {
x = "You pressed Cancel!";
}
document.getElementById("demo").innerHTML = x;
}
</script>
on the PHP page i call it like this :
print "<a href='http://www.google.com' onclick='return show_confirm();'> Google </a>";
$userAnswer = ???;
How do I know if the user pressed OK or CANCEL? (so that i can do different treatement).
Thanks in advance.
</div>
User confirm on client side, and you want to do something on the server side. As the comments says, use AJAX (I would suggest you to use a JS framework like jquery).
if (confirm("Press a button!") == true) {
// OK
} else {
// CANCEL
}
PHP is done before the page is shown, hence it is a pre-processor. It cannot respond to items when the page is show - that is the role of Javascript.
The best of doing this is to define a div (id answer for example), have your javascript pass something to a php page and put the answer in the div. Something like:
function show_confirm() {
var x;
if (confirm("Press a button!") == true) {
x = 1;
} else {
x = 0; }
$("#answer").load("yourphpprocesspage.php?answer=" + x);
}
Simply then write something in PHP for the process page like:
<?php
if ($_GET['answer'] == 1)
{$text = "You pressed confirm";}
else
{$text = "Your pressed cancel"; }
?>
Then in the body of your processing page add after the
<?php echo $text; ?>
This solution is quite simple and can be seen here DEMO
<input type="button" id="myButton" value="Click Me">
The javascript part is:
$("input").on("click", function() {
var output = 1;
if(confirm("You really??"))
{
output=0;
}
alert(output);
});
The output is 0 when the user clicks OK and it is 1 when he clicks Cancel
This is the AJAX POST Request about which you can read here:
$.POST("yourphpfile.php", data, fucntion(response) {
if(!response) {
alert("Server not responding");
}
else {
//Do what ever you want.!!
}
});
Also read this AJAX REQUEST POST Type