I cannot find a way that works to re-populate multiple select boxes, Since it is stored as an array is there a way to cross-check and repopulate the selections that were made? I am trying to answer question 4 from the comments section of the code.
The section of the form that I am trying to repopulate is the like_bands multiple select box
my code:
<?php
session_start();
/*
This page should:
1) Use a cookie (NOT PHP SESSION) that expires a year from now to do the following:
Record the timestamp of the FIRST load of this page (but NOT any subsequent load of this page).
Note: You only need first 3 parameters in setcookie() for this HW.
2) If the suvey was already completed, transfer to third page (thank you page).
That page instructs you to set a cookie that will allow you to detect this.
Recall from the CRUD example how page transfers are done in PHP:
header("Location: URL");
3) The form in this page should submit to THIS PAGE, and then transfer to hw_page2.php
after saving stuff to PHPs built-in $_SESSION superglobal.
The data will then be available in all the other pages (remember no database is allowed for this HW).
4) If the button in the 2nd page is clicked to come back to this page, the
Session data should re-populate into the form.
*/
if (!isset($_COOKIE['load_date'])) {
setcookie('load_date', time(), time() + (86400 * 365));
}
$load_date = $_COOKIE['load_date'];
$is_cool = $_POST['is_cool'];
var_dump($is_cool);
$bands = $_POST['like_bands'];
$band_list = "";
foreach ($bands as $band) {
$band_list .= $band. ", ";
}
$other_band = $_POST['other_band'];
echo $other_band;
$_SESSION['is_cool'] = $is_cool;
$_SESSION['bands'] = $band_list;
$_SESSION['other_band'] = $other_band;
?>
<!DOCTYPE html>
<html>
<head>
<title>User Profile</title>
</head>
<body>
<h3><?=$message?></h3>
User Profile:
<br><br>
<form action="hw_page1.php" method="POST" name="form1" onsubmit="return validate_form()">
<input type="hidden" name="task" value="process_profile">
<?php if ($is_cool != null) {?>
<input type="checkbox" name="is_cool" value="yes" checked='checked'>
Are you cool?
<?php } else { ?>
<input type="checkbox" name="is_cool" value="yes">
Are you cool?
<?php }?>
<br><br>
What Bands do you like?
<br>
<select name="like_bands[]" multiple> <small>* Required Field</small>
<option value="Sabbath">Black Sabbath</option>
<option value="Mastodon">Mastodon</option>
<option value="Metallica">Metallica</option>
<option value="Swift">Taylor Swift</option>
</select>
<br><br>
Favorite band not in the above list.
<br>
<input type="text" name="other_band" value="<?=$other_band?>">
<br><br>
<button type="submit"> Continue/Confirm </button>
</form>
<script>
//////////////////////////////////////////////////////////////////////////////////////////////////////////
// Client-side form validation
// Don't change the names of stuff in the form, and you won't have to change anything below
// Used built-in JS instead of JQuery or other validation tool
//////////////////////////////////////////////////////////////////////////////////////////////////////////
function validate_form() {
var form_obj = document.form1;
var count_liked = 0;
for (var i=0 ; i < form_obj['like_bands[]'].options.length ; i++ ) {
if (form_obj['like_bands[]'].options[i].selected) {
count_liked++;
}
}
if (count_liked == 0) {
alert("You must choose a band from the menu.");
return false; // cancel form submission
}
return true; // trigger form submission
}
</script>
<?php
/*if (isset($_POST['like_bands'])) {
header('Location: hw_page2.php');
}*/
?>
</body>
</html>
Related
I am supposed to have my form elements repopulate using php and html only after I click the link from page two. However, none of the fields are repopulating. Please help me!!?
Page 1:
<?php
session_start();
?>
<?php
/*
This page should:
1) Use a cookie (NOT PHP SESSION) that expires a year from now to do the following:
Record the timestamp of the FIRST load of this page (but NOT any subsequent load of this page).
Note: You only need first 3 parameters in setcookie() for this HW.
2) If the suvey was already completed, transfer to third page (thank you page).
That page instructs you to set a cookie that will allow you to detect this.
Recall from the CRUD example how page transfers are done in PHP:
header("Location: URL");
3) The form in this page should submit to THIS PAGE, and then transfer to hw_page2.php
after saving stuff to PHPs built-in $_SESSION superglobal.
The data will then be available in all the other pages (remember no database is allowed for this HW).
4) If the button in the 2nd page is clicked to come back to this page, the
Session data should re-populate into the form.
*/
if (!isset($_COOKIE['load_date'])) {
setcookie('load_date', time(), time() + (86400 * 365));
}
?>
<!DOCTYPE html>
<html>
<head>
<title>User Profile</title>
</head>
<body>
<h3><?=$message?></h3>
User Profile:
<?php
$load_date = $_COOKIE['load_date'];
$_SESSION['is_cool'] = $_POST['is_cool'];
$_SESSION['like_bands'] = $_POST['like_bands'];
$_SESSION['other_band'] = $_POST['other_band'];
$is_cool = $_SESSION['is_cool'];
$bands = $_SESSION['like_bands'];
$other_band = $_SESSION['other_band'];
print_r($bands);
echo $other_band;
echo $is_cool;
?>
<br><br>
<form action="hw_page1.php" method="POST" name="form1" onsubmit="return validate_form()">
<input type="hidden" name="task" value="process_profile">
<input type="checkbox" name="is_cool" value= "yes" <?php if ($is_cool == 'yes') {
echo 'checked = "yes"';
}?>>
Are you cool?
<br><br>
What Bands do you like?
<br>
<select name="like_bands[]" multiple> <small>* Required Field</small>
<option value="Sabbath" <?php if (isset($_SESSION['like_bands']) && in_array("Mastodon", $bands)) {
echo 'selected';
} ?>> Black Sabbath</option>
<option value="Mastodon" <?php if (isset($_SESSION['like_bands']) && in_array("Mastodon", $bands)) {
echo 'selected';
} ?> >Mastodon</option>
<option value="Metallica" <?php if (isset($_SESSION['like_bands']) && in_array("Metallica", $bands)) {
echo 'selected';
} ?> >Metallica</option>
<option value="Swift" <?php if (isset($_SESSION['like_bands']) && in_array("Swift", $bands)) {
echo 'selected';
} ?> >Taylor Swift</option>
</select>
<br><br>
Favorite band not in the above list.
<br>
<input type="text" name="other_band" value="<?=$other_band?>">
<br><br>
<button type="submit" name= 'submit' value = 'submit'> Continue/Confirm </button>
</form>
<script>
//////////////////////////////////////////////////////////////////////////////////////////////////////////
// Client-side form validation
// Don't change the names of stuff in the form, and you won't have to change anything below
// Used built-in JS instead of JQuery or other validation tool
//////////////////////////////////////////////////////////////////////////////////////////////////////////
function validate_form() {
var form_obj = document.form1;
var count_liked = 0;
for (var i=0 ; i < form_obj['like_bands[]'].options.length ; i++ ) {
if (form_obj['like_bands[]'].options[i].selected) {
count_liked++;
}
}
if (count_liked == 0) {
alert("You must choose a band from the menu.");
return false; // cancel form submission
}
return true; // trigger form submission
}
</script>
<?php
$_SESSION['is_cool'] = $is_cool;
$_SESSION['like_bands'] = $bands;
$_SESSION['other_band'] = $other_band;
echo $_SESSION['is_cool'];
if (isset($_SESSION['like_bands'])) {
header('Location: hw_page2.php');
}
?>
</body>
</html>
My second Page:
<?php
session_start();
/*
This page should:
1) Transfer back to hw_page1.php if loaded directly without the survey being completed (no survey data in session).
2) Display the Survey Data submitted from the previous page.
3) The form in this page should submit to THIS PAGE.
Use PHP to validate that the form below is completed.
Validate that the signature is not the empty string or only blank spaces (use PHP trim() function)
And of course validate that the checkbox was checked.
If the validation passes, save the signature into SESSION ande transfer to hw_page3.php.
If the validation fails, don't transfer.
Instead, back through to the form in this page WITH an appropriate message.
In that case, the Survey Data MUST also re-display in this page.
Note:
hw_page1.php used client-side JavaScript validation to ensure that all data was collected.
For the form below. do NOT use client-side JavaScript validation, but rather use PHP as instructed above.
Client-side validation is convenient for the end user, but can be bypassed by someone with know-how.
*/
?>
<?php
if (!isset($_SESSION['is_cool']) and !isset($_SESSION['like_bands'])) {
header('Location: hw_page1.php');
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Verify Profile</title>
</head>
<body>
<?php
$is_cool = $_SESSION['is_cool'];
$bands = $_SESSION['like_bands'];
$other_band = $_SESSION['other_band'];
echo $is_cool;
print_r($bands);
echo $other_band;
$_SESSION['is_cool'] = $is_cool;
$_SESSION['like_bands'] = $bands;
$_SESSION['other_band'] = $other_band;
$bandslist = "";
foreach ($bands as $band) {
$bandslist .= "$band, ";
}
?>
<!-- Display Survey Data Here -->
<table width="" border="1" cellspacing="0" cellpadding="5">
<tr valign="top">
<td>Are you cool?</td>
<td>Liked Bands</td>
<td>Other Favorite Band</td>
</tr>
<tr valign="top">
<td><?= $_SESSION['is_cool']; ?></td>
<td><?= $bandslist; ?></td>
<td><?= $other_band; ?></td>
</tr>
</table>
<br><br>
<form action="hw_page2.php" method="GET" >
Verify that your profile data shown above is accurate by signing below.
<br>
<input type="text" name="signature" value="" placeholder="Sign Here">
<br>
<input type="checkbox" name="user_certify" value="yes">
I certify, under penalty of purgery, that my profile is accurate.
<br><br>
<button type="button" onclick="window.location='hw_page1.php';"> Go Back: Edit Profile Before Signing </button>
<!-- This is NOT a Submit Button! -->
<br>
<button type="submit"> Record Profile </button>
<!-- This is obviously -->
</form>
</body>
</html>
Please help me figure out where I am making a mistake! I have been working on it for days but I cannot figure out the answer.
I would really appreciate any help if possible!
This is the question:
Use a cookie (NOT PHP SESSION) that expires a year from now to do the following:
Record the timestamp of the FIRST load of this page (but NOT any subsequent load of this page).
The code:
<!DOCTYPE html>
<html>
<head>
<title>User Profile</title>
</head>
<body>
<h3><?=$message?></h3>
User Profile:
<br><br>
<form action="" method="POST" name="form1" onsubmit="return validate_form()">
<input type="hidden" name="task" value="process_profile">
<input type="checkbox" name="is_cool" value="yes">
Are you cool?
<br><br>
What Bands do you like?
<br>
<select name="like_bands[]" multiple> <small>* Required Field</small>
<option value="Sabbath">Black Sabbath</option>
<option value="Mastodon">Mastodon</option>
<option value="Metallica">Metallica</option>
<option value="Swift">Taylor Swift</option>
</select>
<br><br>
Favorite band not in the above list.
<br>
<input type="text" name="other_band" value="">
<br><br>
<button type="submit"> Continue/Confirm </button>
</form>
<script>
//////////////////////////////////////////////////////////////////////////////////////////////////////////
// Client-side form validation
// Don't change the names of stuff in the form, and you won't have to change anything below
// Used built-in JS instead of JQuery or other validation tool
//////////////////////////////////////////////////////////////////////////////////////////////////////////
function validate_form() {
var form_obj = document.form1;
var count_liked = 0;
for (var i=0 ; i < form_obj['like_bands[]'].options.length ; i++ ) {
if (form_obj['like_bands[]'].options[i].selected) {
count_liked++;
}
}
if (count_liked == 0) {
alert("You must choose a band from the menu.");
return false; // cancel form submission
}
return true; // trigger form submission
}
</script>
</body>
</html>
Check if the cookie is already set. If not, set the cookie to the current timestamp.
if (!isset($_COOKIE['load_date'])) {
setcookie('load_date', time(), time() + 86400*365);
}
I'm pretty new with PHP, so help please.
I need a web page in php with a checkbox. That page should refresh itself each time I do an action to the checkbox (so for both check or uncheck). Once it’s refreshed the page should keep the latest value of the checkbox.
I tried the following example modifying another code I took from StackOverflow, but it doesn’t works as I wish.
Any suggestion?
<?php
session_start();
$checked = "";
if($_SESSION['myaction'] != $_SESSION['value'])
{
if(isset($_POST['sharks']))
{
$_SESSION['value'] = $_POST['sharks'];
}
else
{
$_SESSION['value'] = '';
echo ":(";
}
$_SESSION['myaction'] = $_SESSION['value'];
}
?>
<form action="" method="POST">
<?php
print '<input name="sharks" type="checkbox" value="1" id="sharks" ';
if ($_SESSION['value'] == 1)
{
echo "checked='checked'";
}
$myaction = 2;
print ">";
?>
</form>
<form method='POST'>
<input name='sharks' type='checkbox' value='1' id='sharks' />
</form>
Some simpple, vanilla, Javascript that makes use of the localStorage ( or sessionStorage ). The click handler will set the checked status and on page load that value will help re-check, or not, the checkbox. Javascript is intended for this sort of purpose - though it is entirely possible to use PHP to re-check the checkbox when the page reloads provided it has some means to check a value against a stored value or a form submission.
document.addEventListener('DOMContentLoaded',()=>{
let chk=document.querySelector('input[type="checkbox"][name="sharks"]');
chk.checked=localStorage.getItem( chk.name )==null || localStorage.getItem( chk.name )=='false' ? false : true;
chk.addEventListener('click',e=>{
localStorage.setItem( chk.name, chk.checked )
location.reload();
});
});
Don't use a checkbox if you don't want the behaviour of a checkbox.
If you are submitting data, use a submit button. Users expect submit buttons to trigger a reload of the page.
<?php
$current_state = get_state_from_database_or_session_or_whatever();
if (isset($_POST['new_state'])) {
if ($_POST['new_state']) == "on") {
$current_state = "off";
} else {
$current_state = "on";
}
update_datebase_or_session_or_whatever_with_new_state($current_state);
}
$other_state = "off";
if ($current_state == "off") {
$other_state = "on";
}
?>
<p>The current state is <?php echo $current_state; ?></p>
<form method="post">
<button name="state" value="<?php echo $other_state; ?>">Set state to <?php echo $other_state; ?></button>
</form>
What you need to is pretty simple- assuming you are submitting the form on the same page.
<?php
$filterUsers=array();
if(isset($_GET['users'])){
foreach($_GET['users'] as $key){
$filterUsers[]=$key;
}
function valueInFilter($value){
if(in_array($value, $filterUsers)){
echo "checked";
}else{
echo "";
}
}
?>
<html>
<head>Filter </head>
<body>
<form method="get" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<input type="checkbox" name="users[]" value="john" id="1" <?php
valueInFilter("john",$filterUsers) ?>>
<label for="1"> John doe</label><br>
<input type="checkbox" name="users[]" value="john" id="2" <?php
valueInFilter("mayor",$filterUsers) ?>>
<label for="2"> John Mayor</label><br>
</form>
</body>
</html>
This is not an job for PHP like Professor Abronsius wrote.
Write it in JavaScript like this:
(() => {
// on page reloaded
const checkboxNode = document.getElementById('sharks')
if (localStorage.getItem('sharkCheckBox')) {
// the checkbox is stored as CHECKED
// e.g. check the checkbox again or what ever:
checkboxNode.checked = true
} else {
// the checkbox is stored as NOT checked
}
// handle the click
checkboxNode.addEventListener('click', function() {
// get the checkbox status
const isChecked = this.checked
// store the checked status inside the browser cache
localStorage.setItem('sharkCheckBox', isChecked)
// there are several ways to to an page reload. Here an example
// see details here https://stackoverflow.com/a/39571605/7993505
location.reload()
})
})()
I'm trying to create a form for entering Computer or Televisions as electronics. I want first the user to select which of the two he's entering, and depending on which one he chooses, he's going to have different stuff to fill in.
I tried to write this but it doesn't work. I get an error on $answer= $_POST['type'];
Please let me know what is wrong, I'm kind of new at php. Thanks.
<div class="form-group">
<h3 style="color:blue;">Type of Item</h1>
<form name ="form1" method ="post">
<input type="radio" name="type" value="Computer"> Computer<br>
<input type="radio" name="type" value="Television"> Television<br>
</form>
</div>
<?php
$answer = $_POST['type'];
if ($answer == "Computer") {
//show stuff
}
else {
//show other stuff
}
?>
$_POST will be empty until the form is actually submitted. Your form does not have a submit button. That said, this type of task is usually better done in javascript since it doesn't require a full page reload just to open up the next set of options in a form.
Here's an example of how this might work using a simple javascript function:
<script type="text/javascript">
function toggleOptions() {
if ( document.getElementById('type_Computer').checked ) {
document.getElementById('nextSetOfComputerOptions').style.display = '';
} else {
document.getElementById('nextSetOfComputerOptions').style.display = 'none';
}
}
</script>
<input type="radio" name="type" id="type_Computer" value="Computer" onclick="toggleOptions();">
<div id="nextSetOfComputerOptions" style="display:none;">
<!-- more form fields -->
</div>
I'm trying get a form to redirect to a certain page depending on what option is chosen in a select div. When I press submit, it redirects to the home page. I realize it's because it doesn't change $industry_choice until after the I press the button... is there a method to change this the moment you select a value?
Let's say I choose banking, and $industry_choice = "banking".
if(empty($_POST['industry'])) {
$industry_choice = "";
} else {
$industry_choice = $_POST['industry'];
}
<form method="post" action="http://localhost:8888/wordpress/<?php echo $industry_choice ?>">
<select name="industry">
(lots of options here)
</select>
<input type="submit" class="select-industry" value="Select">
</form>
You are doing it wrong. I think you are not clear with the action attibute of the form.
<?php
if(empty($_POST['industry'])) {
$industry_choice = "";
} else {
$industry_choice = $_POST['industry'];
header('Location: http://localhost:8888/wordpress/'.$industry_choice);
}
?>
<form method="post" action="">
<select name="industry">
(options)
</select>
<input type="submit" class="select-industry" value="Select">
</form>
action attribute will redirect to the page you processed the input. After that you will redirect it to targeted location.