$_SESSION() Checkbox doesn’t hold state
I’ve been working on getting forms to hold their data when the back button is pushed. It’s been slow going. I thought I had it down (This entry). But when it came to checkboxes, and selects, I was in for a surprise. Most the code is pretty fundamental.
I was able to get selects to work, by making them dynamic and conditionally adding the “selected” attribute to the selected item.
Regarding what I’ve learned so far, I realize that a checkbox only sends a value if it is checked.
If it’s not checked, it doesn’t send any value at all. So I tried to create a variable based upon the condition of when it was checked. In this case I called it $flag.
Then made a session for that varaiable thinking that it would carry back over if the back button was pushed. However the session variable for it, $_SESSION['flag'] doesn’t carry back over. The box will not remember to be checked.
form.php:
< ?php
// [ START SESSION ]
session_start();
header("Cache-control: private"); // IE 6 Fix.
?>
<html>
<body>
<form method="post" action="preview.php">
Choose #1: <input type="checkbox" name="box1"/><br />
<input type="submit" value="submit"/>
</form>
</body>
</html>
preview.php:
< ?php
// [ START SESSION ]
session_start();
header("Cache-control: private"); // IE 6 Fix.
// actions to take from buttons
if (isset($_POST["goBack"])) { // Go Back and Edit
header("Location: form.php");
} else {
if (isset($_POST["Send"])) { // Process the form
header("Location: process.php");
}
}
// Dynamically Assign Key & Value to each Post - when back button is pushed.
It retains the form data for textboxes only it seems.
foreach($_POST as $key=>$value){
$_SESSION[$key]=$value;
print("$key = $value<br />");
}
?>
<html>
<body>
< ?php
if(isset($_POST['box1'])){
$flag = 'checked';
$_SESSION['flag'] = $flag;
print("<font color=\"red\"><b>box is checked. flag = $_SESSION[flag]</b><br />");
} else {
$flag = 'NOT Checked';
$_SESSION['flag'] = $flag;
print("<font color=\"red\"><b>box is NOT checked. flag = $_SESSION[flag]</b></font><br />");
}
?>
<form method="post" action="preview.php">
<input type="submit" name="goBack" value="Edit"/><input type="submit" name="Send" value="OK"/>
</form>
</body>
</html>
I’m still looking for a solution for this. Now that I think about it, I’m going to imagine that radio’s will have a similar issue. I will post the solution – if I find a workaround.