Bootstrap toggle button status update with AJAX PHP and MySQL

How to make a Bootstrap toggle button with a status update by using PHP, Ajax and MySQL. The toggle button represents on/off which is 1 and 0 in the database.

Updated version with no page re-loading here.

Bootsrap Toggle Ajax PhpThe button will always represent what the value is in the database.

This example is for a mock-up machine state (id=450) i.e on or off

Starting by doing a session start and getting the machine id from the GET parameter id.

<?php
session_start();
$machine_id = $_GET['id'];
?>

Now for the CSS and Jquery links, along with the ajax request to status.php which sets session.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>On off toggle</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootswatch/4.5.0/flatly/bootstrap.min.css"/>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $.ajax({
                type: "GET",
                url: "status.php",
                data: {"id": <?php echo $machine_id;?>},
                success: function (data) {
                    console.log(data)
                }
            });
        });
    </script>
</head>

Check if the form was submitted or otherwise. If the form was submitted then update the value as per the toggle switch, if the page is being loaded not from the form then the status is set from the session.

<?php
if (isset($_POST['form_submit'])) {//Form was submitted
    (isset($_POST['machine_state'])) ? $status = 1 : $status = 0;
    //Update DB
    $db = new PDO('mysql:host=localhost;dbname=testing;charset=utf8mb4', 'root', '');
    $update = $db->prepare("UPDATE `info` SET `status` = ? WHERE `id` = ? LIMIT 1;");
    $update->execute([$status, $machine_id]);
} else {//Page was loaded
    $status = $_SESSION['status'];
}
if ($status) {//status = 1 (on)
    $status_str = "on";
    $checked_status = "checked";
} else {
    $status_str = "off";
    $checked_status = "";
}
?>

The form:

<body>
<div class="container">
    <div class="row text-center">
        <div class="col-12">
            <form method="post">
                <fieldset>
                    <legend>on/off status for machine: <?php echo $machine_id; ?></legend>
                    <div class="form-group">
                        <div class="custom-control custom-switch">
                            <input type="checkbox" class="custom-control-input" id="customSwitch1"
                                   name='machine_state' <?php echo $checked_status; ?>>
                            <label class="custom-control-label"
                                   for="customSwitch1">Currently <?php echo $status_str; ?></label>
                        </div>
                        <input type="hidden" name="form_submit" value="">
                    </div>
                </fieldset>
                <input type="submit" class="btn btn-info btn-sm" name="submit" value="Update"/>
            </form>
        </div>
    </div>
</div>
</body>
</html>

Here is the form with the toggle button. It will be in that state of the status (on or off) upon page load and if updated will switch.

Upon page load, a GET request is sent to staus.php with the machine id.

status.php:

<?php
session_start();
$db = new PDO('mysql:host=localhost;dbname=testing;charset=utf8mb4', 'root', '');
$sel_status = $db->prepare("SELECT `status` FROM `info` WHERE `id` = ? LIMIT 1;");
$sel_status->execute([$_GET['id']]);
$status = $sel_status->fetch()['status'];//1 or 0
$_SESSION['status'] = $status;
echo ($status) ? 'checked' : '';

This file sets the session as the status and will also output either “checked” if status = 1 or will output nothing if status = 0.

The MySQL table:

CREATE DATABASE IF NOT EXISTS `testing`;
USE `testing`;

CREATE TABLE IF NOT EXISTS `info`
(
    `id`     int(11) NOT NULL,
    `status` tinyint(1) DEFAULT 0,
    PRIMARY KEY (`id`)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8mb4;

INSERT INTO `info` (`id`, `status`) VALUES (450, 0);

The full code:

<?php
session_start();
$machine_id = $_GET['id'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>On off toggle</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootswatch/4.5.0/flatly/bootstrap.min.css"/>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $.ajax({
                type: "GET",
                url: "status.php",
                data: {"id": <?php echo $machine_id;?>},
                success: function (data) {
                    console.log(data)
                }
            });
        });
    </script>
</head>
<?php
if (isset($_POST['form_submit'])) {//Form was submitted
    (isset($_POST['machine_state'])) ? $status = 1 : $status = 0;
    //Update DB
    $db = new PDO('mysql:host=localhost;dbname=testing;charset=utf8mb4', 'root', '');
    $update = $db->prepare("UPDATE `info` SET `status` = ? WHERE `id` = ? LIMIT 1;");
    $update->execute([$status, $machine_id]);
} else {//Page was loaded
    $status = $_SESSION['status'];
}
if ($status) {//status = 1 (on)
    $status_str = "on";
    $checked_status = "checked";
} else {
    $status_str = "off";
    $checked_status = "";
}
?>
<body>
<div class="container">
    <div class="row text-center">
        <div class="col-12">
            <form method="post">
                <fieldset>
                    <legend>on/off status for machine: <?php echo $machine_id; ?></legend>
                    <div class="form-group">
                        <div class="custom-control custom-switch">
                            <input type="checkbox" class="custom-control-input" id="customSwitch1"
                                   name='machine_state' <?php echo $checked_status; ?>>
                            <label class="custom-control-label"
                                   for="customSwitch1">Currently <?php echo $status_str; ?></label>
                        </div>
                        <input type="hidden" name="form_submit" value="">
                    </div>
                </fieldset>
                <input type="submit" class="btn btn-info btn-sm" name="submit" value="Update"/>
            </form>
        </div>
    </div>
</div>
</body>
</html>