views:

2485

answers:

2

Is there a PHP version of JavaScript's confirm() function?
If not, what are my other options or how do I make something similar to the confirm()?

+6  A: 

Because PHP is a server-side language (all the PHP code is executed on the server, and the output of the code is sent to the client), you'd have to make an HTML form with OK/Cancel buttons that would submit to your PHP page. Something like this:

confirm.php:

<p>Are you sure you want to do this?</p>

<form action="page2.php" method="post">
    <input type="submit" name="ok" value="OK" />
    <input type="submit" name="cancel" value="Cancel" />
</form>

page2.php:

<?php

if (isset($_POST['ok'])) {
    // They pressed OK
}

if (isset($_POST['cancel'])) {
    // They pressed Cancel
}

?>
yjerem
type=button does not send form to the server. You should use type=submit. And you can use just one form for both button.
porneL
Oh right, type=submit is what I meant, thanks (I fixed it).
yjerem
No need to have two form blocks, 1 will do with a <br /> between the buttons, or perhaps wrapping the buttons in <p> tags (assuming you do in fact need them on separate lines)
Karan
Ok, I actually did have one form with two buttons originally, but I didn't know for sure whether it would submit the values of both buttons or just submit the value of the one that was clicked. So since you both agree it should be one form, then I guess what I worried about shouldn't be a problem.
yjerem
+1  A: 

Using the same answer from the previous post adding some error treatment and safety:

<form action="page2.php" method="post">
   Your choice: <input type="radio" name="choice" value="yes"> Yes <input type="radio" name="choice" value="no" /> No
    <button type="submit">Send</button>
</form>

And in your page2.php:

if (isset($_POST['choice']) /* Always check buddy */) {
    switch($_POST['choice']) {
        case 'yes':
            /// Code here
            break;
        case 'no':
            /// Code here
            break;
        default:
            /// Error treatment
            break;
    }
}
else {
    // error treatment
}
José Leal