[SOLVED] How can I retain checkbox value after page refresh?

Issue

I want to retain the value of multiple checkbox after the page is refreshed. Based on my research, I found two viable options 1) using session variables or 2) via localStorage. I decided to choose localStorage since it is optimized for modern browsers. I wrote the code based on this example: Keep checkbox checked even after page refresh? .
When I toggle the switch on/off it works normally. But, if I toggle it on and refresh the page (going in the address bar and press enter), it get unchecked and the value in the database is set to 0 (from 1).

I don’t what is wrong with the code. Can someone please advise me?

Thanks

<?php
$servername = "localhost";
$username = "xxxxx";
$password = "xxxxx";
$database ="xxxxx";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);

// Check connection
if (!$conn) {
  die("Connection failed: " . mysqli_connect_error());
}
//echo "Connected successfully";
?> 
<!DOCTYPE html>  
 <html>  
 <head>  
      <meta charset="utf-8">  
      <meta name="viewport" content="width=device-width, initial-scale=1">  
     <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
 </head>  
 <body>  

<?php
if(isset($_POST) && count($_POST) >= 0){
    
    if (isset($_POST['checkbox1'])) {

        $query1 = "UPDATE switch_status SET status = 1 WHERE switch_id = 1";
    } else {
        $query1 = "UPDATE switch_status SET status = 0 WHERE switch_id = 1";
    }
    $result1 = mysqli_query($conn, $query1) or die(mysqli_error());
}
     
?>


<form id="form" action="" method="POST" >

        <label>
            Checkbox 1
            <input type="checkbox"  id = "check" name="checkbox1" value="1" autocomplete="off" onchange="document.getElementById('form').submit();"
                <?php if(isset($_POST['checkbox1'])) { echo 'checked="checked"'; } ?>>
        </label>



    </form>
<script>
$('#check').on('click', function(){

  if(localStorage.getItem("checkedbox") == 'true') {
    $(this).prop(checked, 'false');
    localStorage.setItem("checkedbox", 'false');

  }
  else {
    $(this).prop(checked, 'true');
     localStorage.setItem("checkedbox", 'true');
  }

})
</script>
 </body>  
 </html>  
 

Solution

For those wondering, I solved my issue by using session variables instead of the localStorage data. This was done by following these threads: Store a checked checkbox from a form in a session and keeping checked checkbox state unless unchecked.

Thank you to everyone that helped me.

Answered By – Sur202

Answer Checked By – Pedro (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *