0

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>
giofon
  • 1
  • 1
  • Any interaction with the page ( ie: checkbox ) should be handled with javascript – Professor Abronsius Feb 13 '21 at 16:15
  • my intention is to use javascript only for graphical purpose, i would like php to manage the entire process flow. The example i took indeed it was only in php but it refreshes the page with a button. I need something similar but without button only a checkbox. – giofon Feb 13 '21 at 16:30
  • 1
    a `checkbox` has no inherent means of submitting a form or refreshing a page – Professor Abronsius Feb 13 '21 at 16:31

4 Answers4

0
<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();
        });
});
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46
0

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>
    
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

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>
-1

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()
    })
})()
Richard
  • 618
  • 1
  • 9
  • 15