Select a category, send its numeric ID to the PHP endpoint, and render the returned JSON without inserting server data as HTML.
async function loadRecords() {
const catId = document.getElementById('cat_id').value;
const params = new URLSearchParams({ cat_id: catId });
const response = await fetch(`ajax-listbox-demo2.php?${params}`);
const payload = await response.json();
if (!response.ok) throw new Error(payload.value.message);
// Build table cells with textContent from payload.data.
}
cat_id on the server and uses a prepared statement when filtering by category.This example displays countries linked to a selected continent. Choosing Show All sends cat_id=0 and returns all available records.
config.php : Database connection settings for the downloadable example
ajax-listbox-demo.php : Category selector and JavaScript renderer
ajax-listbox-demo2.php : PHP endpoint that validates cat_id and returns JSON
plus2_cat stores each category and plus2_subcat stores linked records through cat_id.
$catIdRaw = $_GET['cat_id'] ?? '0';
if (filter_var($catIdRaw, FILTER_VALIDATE_INT) === false || (int)$catIdRaw < 0) {
http_response_code(400);
exit;
}
$catId = (int) $catIdRaw;
if ($catId > 0) {
$stmt = $dbo->prepare('SELECT subcat_id, subcat_name FROM plus2_subcat WHERE cat_id = :cat_id ORDER BY subcat_name');
$stmt->execute([':cat_id' => $catId]);
} else {
$stmt = $dbo->prepare('SELECT subcat_id, subcat_name FROM plus2_subcat ORDER BY subcat_name');
$stmt->execute();
}
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
header('Content-Type: application/json; charset=UTF-8');
echo json_encode([
'data' => $result,
'value' => ['cat_id' => $catId, 'message' => '']
]);
Use DOM methods such as createElement() and textContent for database values. This avoids treating returned names as HTML.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| zeno | 29-04-2012 |
| Thanks for the code. But how will I do if I want to have 2 dropdown which are populated with database and based on the selection of the two dropdown the result is display. Please help me. | |
| Ayaz Khan | 08-10-2016 |
| Hello friend, I want to do this in Zendframework 2, How it is possible? please help me. | |
| Website Designing | 12-08-2017 |
| Great!! This tutorial is massively helpful. This was so easy to follow and exactly what I was looking for. It just made my work easier. Thanks. | |