Refresh a PHP page after checking/unchecking a checkbox - php

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()
})
})()

Related

PHP Parse Error: script can not get data from form

I tried to collect data from this form,as a quiz:
<form action="quiz.php" method = "post" id = "questions" name = "quiz">
<label>This is a quiz:</label><br>
<input type="radio" name = "vote1" value = "Yes"/><label>Yes</label>
<input type="radio" name = "vote1" value = "No"/><label>No</label>
<button type = "submit" name="send">Submit</button>
</form>
And I sent it to this php script:
<html>
<?php
if (isset($_POST['send'])){
if (isset($_POST["quiz"])){
if (isset($_POST['vote1'])){
if ($_POST['vote1'] === "Yes"){
echo "Yes,that is the answer.";
}else{
echo "Yes,that is the answer";
};
}};};
?>
<body>
</body>
</html>
But it didn't generate any HTML...
Although you can see in the url,that it definetely tried to pick up data:
http://localhost/php/quiz.php?vote1=Yes&send=
But it didn't really send data and I don't know what to do in that case,can anyone help me?...
It was not displaying output because of if (isset($_POST["quiz"]))
Below code of yours will work, and will display you echo result.
<html>
<?php
if (isset($_POST['send'])) {
if (isset($_POST['vote1'])) {
if ($_POST['vote1'] == "Yes") {
echo "Yes,that is the answer.";
} else {
echo "Yes,that is the answer";
};
}
};
?>
<body>
</body>
</html>
If the form method was GET you would get a querystring as described but the above form uses POST so that would not happen. The only form element of interest in the POST array really is vote1 so ensure that is present using isset - the other items such as the button or the form name ( ? which won't be there, ever! ) are not relevant.
A label element should be associated with a form element in one of two ways: either using the for=ID_of_element type syntax or by having the element as a child, as below.
<html>
<head>
<title>Quiz></title>
</head>
<body>
<form action="quiz.php" method="post" id="questions" name="quiz">
<h1>This is a quiz:</h1>
<label><input type="radio" name="vote1" value="Yes"/>Yes</label>
<label><input type="radio" name="vote1" value="No"/>No</label>
<button type = "submit" name="send">Submit</button>
</form>
<?php
if( isset( $_POST['vote1'] ) ){
$msg='';
switch( strtolower( $_POST['vote1'] ) ){
case 'yes':$msg='Yes,that is the answer.';break;
case 'no':$msg='Sorry, that is not correct';break;
}
echo $msg;
}
?>
</body>
</html>

How to repopulate multiple select boxes and checkboxes

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>

Re-populate fields after form submission and redirection PHP ONLY

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.

Conditional Javascript Redirect With Back Button Checker

I have done a conditional redirect with javascript (depending of referer). However now I need to detect if user got redirected and then he clicked back button and got again to the page he has been redirected from. In this case I need no to redirect him again.
I have found a solution here - but I am failed to combine php and javascript properly, so there is always an error - How do I detect if a user has got to a page using the back button?
Code:
<form name="ignore_me">
<input type="hidden" id="page_is_dirty" name="page_is_dirty" value="0" />
</form>
<script language="javascript" type="text/javascript">
var dirty_bit = document.getElementById('page_is_dirty');
if (dirty_bit.value == '1') {
document.write("<p>Do Not Redirect</p>");
}
else {
<?php if((stristr($_SERVER['HTTP_REFERER'],"thoughts") != FALSE) { ?>
<?php $setupform = '<form id="form1" method="post" action="http://yahoo.com">'; ?>
<?php $submitform = 'document.getElementById(\'form1\').submit(); </form>'; ?>
<?php echo $setupform; ?>
<?php echo $submitform; ?>
<?php } ?>
}
function mark_page_dirty() {
dirty_bit.value = '1';
}
</script>
What is wrong here?
The error is that it simply doesn't redirect - it gives a blank page with code on it:
<form name="ignore_me">
<input type="hidden" id="page_is_dirty" name="page_is_dirty" value="0" />
</form>
<script language="javascript" type="text/javascript">
var dirty_bit = document.getElementById('page_is_dirty');
if (dirty_bit.value == '1') {
document.write("<p>My First JavaScript</p>");
}
else {
<form id="form1" method="post" action="http://yahoo.com">document.getElementById('form1').submit(); </form>
}
function mark_page_dirty() {
dirty_bit.value = '1';
}
I took a look at your code and here are some points:
When mixing PHP and JS, remember, that PHP code will be executed first, it will not read any of JS statements
You put a block of PHP code into if statement of JS.
Here is a possible solution for you:
PHP logic first:
$redir = false ;
if((stristr($_SERVER['HTTP_REFERER'],"thoughts"))) {
$redir = true ;
}
HTML form:
<form id="check" action="a.php" method="post">
<input type="hidden" name="durty_bit" value="1" />
</form>
JS check:
var check = getElementById("check") ;
if (check && check.durty_bit == 1){
document.write("<p>Do Not Redirect</p>");
} else {
<?php if ($redir){ ?>
document.write('<form id="form1" method="post" action="http://yahoo.com"> </form>');
document.getElementById("form1").submit() ;
<?php } ?>
}

How to manage $_POST[] and $_SESSION[] to remember forms across multiple pages in PHP?

I'm playing with small exercise to understand sessions and posts, but can't get them to behave together. Can you help?
Situation
I have the following pages
Page 1
Page 2
On page 1 I have a single input form. The input is a checkbox, ex:
<input type="checkbox" name="test" >
I want to be able to arrive at page 1 without receiving errors
I would like the unselected state of the checkbox to have a value of 0, and the selected state a value of 1
Whatever value is assigned (by way of the checkbox), I would like that value stored in a session that can travel from page 1 to page 2 and back.
Once a session value is stored, I would like to select or deselect the checkbox on page 1 to change the value, allowing me to travel from page 1 to page 2 and back with the new value.
Here is my code for this (which does not work):
Page 1
Note: I have this code on the same page as the form. The checkbox name="test"
if (isset($_POST['test']))
{
$_SESSION['test'] = $_POST['test'];
}
if (empty($_SESSION['test']))
{
$_SESSION['test'] = 0;
}
else
{
$_SESSION['test'] = 1;
}
var_dump($_SESSION['test']);
Page 2
var_dump($_SESSION['test']);
Thanks in advance for you help.
UPDATE
If you would like to see the full code for both pages, I have posted them here:
Page 1:
http://www.diigo.com/item/note/17zt6/ux45
Page 2:
http://www.diigo.com/item/note/17zt6/gv6k
<?php
session_start();
if (isset($_POST['submit']) && isset($_POST['test']))
{
$_SESSION['test'] = true; // sets the session if the checkbox was set
} elseif (isset($_POST['submit']) && !isset($_POST['test'])) {
if (isset($_SESSION['test'])) unset($_SESSION['test']);
}
$checked = '';
if (isset($_SESSION['test'])) {
$checked = 'checked="checked"'; // check the checkbox by default if the session is set
}
echo '<input type="checkbox" name="test" '.$checked.'>';
echo '<input type="submit" name="submit" value="Submit">';
Use this code for your page1.php
<?php
session_start();
if(isset($_POST['submit']))
{
if (isset($_POST['test']))
{
$_SESSION['test'] = $_POST['test'];
}
else
{
$_SESSION['test'] = 0;
}
}
if (empty($_SESSION['test']))
{
$_SESSION['test'] = 0;
$checked = '';
}
else
{
$_SESSION['test'] = 1;
$checked = 'checked="checked"';
}
var_dump($_SESSION['test']);
?>
<!DOCTYPE html>
<html>
<head>
<title>Page 1</title>
</head>
<body>
<form action="page1.php" method="post">
Test:
<input type="checkbox" name="test" <?php echo $checked; ?>>
<input type="submit" name="submit" value="Test!">
</form>
<br />
Continue
</body>
</html>
Why not use if (!isset($_SESSION['test'])) instead of if (empty($_SESSION['test'])) ?

Categories