I have an input checkbox styled as a switch
<input id="Kim1043" class="form-check-input" onclick="toggleStatus(this) type="checkbox" name="Kim1043">
<label id="user-status-toggle" for="Kim1043"> $value['status'] </label>
where $value['status']
exists in two states: Active
and Inactive
, information coming from a database.
I am trying to fetch a POST request with JavaScript so that when I toggle the switch, the database would be updated with the current status of the switch. I have a PHP function that would update the database.
function toggleStatus(radio) {
var toggle = document.getElementById('user-status-toggle');
if (radio.checked) {
fetch("/dashboard?php=salespeople-tb", { method: "POST", body: JSON.stringify({ status: "Active" }) })
.then((resp)) => { toggle.textContent = "Active" })
.catch((resp) => { toggle.textContent = "Error" })
} else {
fetch("/dashboard?php=salespeople-tb", { method: "POST", body: JSON.stringify({ status: "Inactive" }) })
.then((resp)) => { toggle.textContent = "Inactive" })
.catch((resp) => { toggle.textContent = "Error" })
}
Then, this is the PHP code:
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$js_response = $_POST["Kim1043"];
return $js_response;
}
I don't know why it's not working.
TL;DR I'm trying to run a PHP function when the switch is toggled.