Live toggle button status update with AJAX

How to make a live Bootstrap toggle button switch update by using Ajax and jQuery. The toggle button updates live to the database with no page reloading needed.

I have made a similar post in the past, however this version updates and shows the status with no page reloading or form submission.

CodePen Link.

jQuery live toggle button update database AJAX

Javascript

Dealing with a Bootstrap toggle switch is done by treating it like a checkbox, selecting a checkbox input with jQuery is done with

$('#elementId').prop('checked', true);

Unchecking it:

$('#elementId').prop('checked', false);

Monitoring a change in its checked status:

$('#formId :checkbox').change(function () {
    if (this.checked) {
        alert('checked');
    } else {
        alert('NOT checked');
    }
});

Now an action can be done depending on if the toggle went to “off” or slid across to the on/active/checked state.

A status of 1 means on/active/checked and 0 is off/in-active/un-checked.

Full script and functions:

function putStatus() {
    $.ajax({
        type: "GET",
        url: "https://peachpuff.srv3r.com/api/index.php",
        data: {toggle_select: true},
        success: function (result) {
            if (result == 1) {
                $('#customSwitch1').prop('checked', true);
                statusText(1);
            } else {
                $('#customSwitch1').prop('checked', false);
                statusText(0);
            }
            lastUpdated();
        }
    });
}

function statusText(status_val) {
    if (status_val == 1) {
        var status_str = "On (1)";
    } else {
        var status_str = "Off (0)";
    }
    document.getElementById("statusText").innerText = status_str;
}

function onToggle() {
    $('#toggleForm :checkbox').change(function () {
        if (this.checked) {
            //alert('checked');
            updateStatus(1);
            statusText(1);
        } else {
            //alert('NOT checked');
            updateStatus(0);
            statusText(0);
        }
    });
}

function updateStatus(status_val) {
    $.ajax({
        type: "POST",
        url: "https://peachpuff.srv3r.com/api/index.php",
        data: {toggle_update: true, status: status_val},
        success: function (result) {
            console.log(result);
            lastUpdated();
        }
    });
}

function lastUpdated() {
    $.ajax({
        type: "GET",
        url: "https://peachpuff.srv3r.com/api/index.php",
        data: {toggle_updated: true},
        success: function (result) {
            document.getElementById("updatedAt").innerText = "Last updated at: " + result;
        }
    });
}

$(document).ready(function () {
    //Called on page load:
    putStatus();
    onToggle();
    statusText();
});

Upon page load the status is fetched and applied along with the latest updated timestamp. When the toggle is interacted with the database gets updated and the new updated timestamp fetched and displayed.

Source HTML with Bootstrap:

<div class="container">
  <div class="row text-center">
    <div class="col-12">
      <form method="post" id="toggleForm">
        <fieldset>
          <legend>on/off status for machine 1</legend>
          <div class="form-group">
            <div class="custom-control custom-switch">
              <input type="checkbox" class="custom-control-input" id="customSwitch1" name='machine_state'>
              <label class="custom-control-label" id="statusText" for="customSwitch1"></label>
            </div>
          </div>
        </fieldset>
      </form>
      <p class="text-center" id="updatedAt">Last updated at: </p>
    </div>
  </div>
</div>

The PHP for Ajax calls (API):

<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');

$db = new PDO('mysql:host=127.0.0.1;dbname=DATABASE;charset=utf8mb4', 'USERNAME', 'PASSWORD');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['toggle_update'])) {
        $update = $db->prepare("UPDATE `toggle` SET `status` = ? WHERE `id` = 1 LIMIT 1;");
        $update->execute([$_POST['status']]);
        echo json_encode($_POST);
    }
} elseif ($_SERVER['REQUEST_METHOD'] === 'GET') {
    if (isset($_GET['toggle_select'])) {
        $select = $db->prepare("SELECT `status` FROM `toggle` WHERE `id` = 1 LIMIT 1;");
        $select->execute();
        echo json_encode($select->fetchColumn());
    } elseif (isset($_GET['toggle_updated'])) {
        $select = $db->prepare("SELECT date_format(updated, '%e %b %l:%i:%s %p') as updated FROM `toggle` WHERE `id` = 1 LIMIT 1;");
        $select->execute();
        echo json_encode($select->fetchColumn());
    }
} else {
    echo json_encode(array());
}

The MySQL sample table:

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET NAMES utf8 */;
/*!50503 SET NAMES utf8mb4 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;


-- Dumping database structure for api
CREATE DATABASE IF NOT EXISTS `api` /*!40100 DEFAULT CHARACTER SET latin1 */;
USE `api`;

-- Dumping structure for table api.toggle
CREATE TABLE IF NOT EXISTS `toggle` (
  `id` int(11) DEFAULT NULL,
  `status` tinyint(4) DEFAULT '0',
  `updated` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- Dumping data for table api.toggle: ~0 rows (approximately)
/*!40000 ALTER TABLE `toggle` DISABLE KEYS */;
INSERT INTO `toggle` (`id`, `status`, `updated`) VALUES
  (1, 1, '2020-11-23 04:55:22');
/*!40000 ALTER TABLE `toggle` ENABLE KEYS */;

/*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */;
/*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;