Display Linked Database Records with AJAX and PHP

Load linked records as JSON

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.
}
The endpoint validates 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.

Demo of AJAX listbox script

Files used

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

Database tables

plus2_cat stores each category and plus2_subcat stores linked records through cat_id.

Validate the category 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;

Use a prepared query

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);

Return JSON

header('Content-Type: application/json; charset=UTF-8');
echo json_encode([
    'data' => $result,
    'value' => ['cat_id' => $catId, 'message' => '']
]);

Render returned records safely

Use DOM methods such as createElement() and textContent for database values. This avoids treating returned names as HTML.

Ajax Listbox script download
The dump file to create MySQL tables is here.
Ajax Json XML


Subscribe to our YouTube Channel here



plus2net.com







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.




PHP video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer