Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Created May 31, 2023 05:55
Show Gist options
  • Save code-boxx/0b17c8517478082f4e8580fd052377f2 to your computer and use it in GitHub Desktop.
Save code-boxx/0b17c8517478082f4e8580fd052377f2 to your computer and use it in GitHub Desktop.
PHP AJAX Dependent Dropdown

PHP AJAX DEPENDENT DROPDOWN

https://code-boxx.com/dependent-dropdown-ajax-php-mysql/

NOTES

  1. Create a test database and import 1-db.sql.
  2. Change the database settings in 2-lib.php to your own.
  3. Launch 4-selector.html in the browser. Captain Obvious – Use http:// not file://.

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

-- (A) CATEGORY TABLE
CREATE TABLE `category` (
`id` bigint(20) NOT NULL,
`parent` bigint(20) NOT NULL DEFAULT 0,
`name` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `category`
ADD PRIMARY KEY (`id`),
ADD KEY `parent` (`parent`),
ADD KEY `name` (`name`);
ALTER TABLE `category`
MODIFY `id` bigint(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;
-- (B) DUMMY DATA
INSERT INTO `category` (`id`, `parent`, `name`) VALUES
(1, 0, 'Electronics'),
(2, 0, 'Sports'),
(3, 1, 'Mobile'),
(4, 1, 'Tablet'),
(5, 1, 'Laptop'),
(6, 1, 'Desktop'),
(7, 2, 'Jogging'),
(8, 2, 'Swimming'),
(9, 2, 'Cycling');
<?php
class Category {
// (A) CONSTRUCTOR - CONNECT TO DATABASE
private $pdo = null;
private $stmt = null;
public $error = null;
function __construct () {
$this->pdo = new PDO(
"mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=".DB_CHARSET,
DB_USER, DB_PASSWORD, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
]);
}
// (B) DESTRUCTOR - CLOSE DATABASE CONNECTION
function __destruct () {
if ($this->stmt !== null) { $this->stmt = null; }
if ($this->pdo !== null) { $this->pdo = null; }
}
// (C) GET BY PARENT CATEGORY
function get ($pid) {
$this->stmt = $this->pdo->prepare("SELECT * FROM `category` WHERE `parent`=?");
$this->stmt->execute([$pid]);
$results = [];
while ($row = $this->stmt->fetch()) { $results[$row["id"]] = $row["name"]; }
return $results;
}
}
// (D) DATABASE SETTINGS - CHANGE TO YOUR OWN!
define("DB_HOST", "localhost");
define("DB_NAME", "test");
define("DB_CHARSET", "utf8mb4");
define("DB_USER", "root");
define("DB_PASSWORD", "");
// (E) NEW CATEGORY OBJECT
$_CAT = new Category();
<?php
// (A) LOAD LIBRARY
require "2-lib.php";
// (B) GET CATEGORIES
$id = isset($_POST["id"]) ? $_POST["id"] : 0 ;
echo json_encode($_CAT->get($id));
<!DOCTYPE html>
<html>
<head>
<title>Dependent Dropdown Selector</title>
<meta charset="utf-8">
<script src="4b-selector.js"></script>
<link rel="stylesheet" href="4c-selector.css">
</head>
<body>
<form onsubmit="return false;">
<label>Main Category</label>
<select id="cat1" onchange="loadcat(2)"></select>
<label>Sub Category</label>
<select id="cat2"></select>
</form>
</body>
</html>
// (A) LOAD CATEGORY SELECTOR
// level 1 = main category
// level 2 = sub category
function loadcat (level) {
// (A1) GET SELECTED PARENT ID
var data = new FormData();
data.append("id", (level==1 ? 0 : document.getElementById("cat1").value));
// (A2) AJAX FETCH CATEGORIES
fetch("3-ajax.php", { method: "POST", body: data })
.then(res => res.json())
.then(cat => {
// (A2-1) UPDATE HTML SELECTOR
let selector = document.getElementById("cat" + level);
selector.innerHTML = "";
for (let i in cat) {
let opt = document.createElement("option");
opt.value = i;
opt.innerHTML = cat[i];
selector.appendChild(opt);
}
// (A2-2) CASCADE LOAD SUB-CATEGORY
if (level==1) { loadcat(2); }
});
}
// (B) INIT LOAD
window.onload = () => loadcat(1);
/* (X) DOES NOT MATTER */
* {
font-family: Arial, Helvetica, sans-serif;
box-sizing: border-box;
}
form {
max-width: 400px;
padding: 30px 20px;
border: 1px solid #e1e1e1;
background: #f2f2f2;
}
label, select {
display: block;
width: 100%;
}
label {
margin: 10px 0;
color: #4a4a4a;
}
form label:first-child { margin-top: 0; }
select {
padding: 10px;
border: 1px solid #d5d5d5;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment