John Davidson

Refresh a PHP page after checking/unchecking a checkbox


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?

$checked = "";

if($_SESSION['myaction'] != $_SESSION['value'])
$_SESSION['value'] = $_POST['sharks'];
$_SESSION['value'] = '';
echo ":(";
$_SESSION['myaction'] = $_SESSION['value'];

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

print '<input name="sharks" type="checkbox" value="1" id="sharks" ';
if ($_SESSION['value'] == 1)
echo "checked='checked'";
$myaction = 2;
print ">";


My Answer:
You can achieve this by using JavaScript to detect when the checkbox is checked or unchecked and then trigger a page refresh. Here's an example code snippet that you can use:


Refresh Page on Checkbox Change

In this code, we have a checkbox element with the id "myCheckbox" and an onchange event listener that calls the refreshPage() function whenever the checkbox is checked or unchecked. The refreshPage() function checks the current state of the checkbox and then reloads the page using location.reload().

This should give you the desired behavior of refreshing the page each time the checkbox is checked or unchecked while keeping the latest value of the checkbox.

Rate this post

3 of 5 based on 7137 votes


© 2024 - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us