0

I have an input checkbox styled as a switch enter image description here

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

Klein -_0
  • 158
  • 1
  • 13
  • Your code for fetch is same in both if and else statements. Hence it always marking as active. Also, you are sending `status` but accessing `Kim1043` in php code – agentofchaoss Dec 07 '21 at 13:45
  • 1
    _Please do not suggest AJAX"_ fyi `fetch()` is AJAX. As for your problem it is because you are trying to post JSON data to php. PHP by default does not parse JSON requests into the super globals like `_POST` or `_REQUEST`. You also do not use the right field names, ie you used `status` to post but `Kim1043` when trying to access the information on the server – Patrick Evans Dec 07 '21 at 13:47
  • It's too complex, try $.post constructs with jquery, easier to understand and use. And come on don't use POST like this. Better if (isset($_POST['somename'])) – Undry Dec 07 '21 at 14:36

0 Answers0