Development

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.

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 */;
Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

2 years ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago