0

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.

SpinaloS
  • 31
  • 1
  • 1
  • 12

3 Answers3

0

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).

AJAX tutorial

if (confirm("Press a button!") == true) {
    // OK
} else {
    // CANCEL
}
0

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; ?>
Jim
  • 596
  • 1
  • 10
  • 36
  • what is the use of checking the condition ==TRUE.?? if confirm is OK the result will be TRUE and and if() will work automatically – MixedVeg Jul 10 '14 at 08:35
  • as he was a newbie I thought I would make it very clear – Jim Jul 10 '14 at 19:13
0

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

MixedVeg
  • 319
  • 2
  • 15