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>
CodePudding user response:
Rather than set the checked property from a PHP post variable (which won't be there if you just refresh the page without submitting), utilize the localStorage data. You can also simplify your function a bit
<form id="form" action="" method="POST">
<label>Checkbox 1 <input type="checkbox" id = "check" name="checkbox1" value="1" autocomplete="off" /> </label>
</form>
<script>
// start by retrieving the current state
$(document).ready(function() {
let isChecked = localStorage.getItem("checkedbox");
// now set it
$('#check').prop('checked', isChecked)
});
$('#check').on('click', function() {
localStorage.setItem("checkedbox", $(this).prop('checked'));
// if you really want to submit the form when someone checks it...
$('form').submit();
})
</script>
CodePudding user response:
I think that the $_POST
superglobal is always defined so your check if(isset($_POST) && count($_POST) >= 0){
will always be true.
Also when you have an unchecked checkbox it is not posted so your $_POST
will be empty for valid requests. Pressing enter in the address bar makes a GET request, but your code can't tell the difference between a GET and POST request, so instead of checking if $_POST is set check the request method.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
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());
}