Lesson 31 of 32Article19 min
AJAX — Database & XML Responses
PHP reads POST/GET params, runs a prepared SELECT, and returns JSON rows. JavaScript renders a table or list.
AJAX with Database
PHP reads POST/GET params, runs a prepared SELECT, and returns JSON rows. JavaScript renders a table or list.
Real-life example: AJAX + database is a live scoreboard — refresh numbers without reloading the whole stadium screen.
search.php — JSON from MySQL
<?php
header("Content-Type: application/json");
require "db.php";
$q = trim($_GET["q"] ?? "");
$stmt = $pdo->prepare(
"SELECT id, name, score FROM students WHERE name LIKE :q LIMIT 10"
);
$stmt->execute([":q" => "%$q%"]);
echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));Client fetch
async function search(name) {
const res = await fetch(`/search.php?q=${encodeURIComponent(name)}`);
const rows = await res.json();
return rows;
}AJAX with XML
Some legacy APIs return XML. PHP can echo XML headers and build strings, or JavaScript parses response as text then DOMParser.
Real-life example: XML AJAX is receiving a fax — older format, but still readable with the right machine.
PHP XML response
<?php
header("Content-Type: application/xml");
echo '<?xml version="1.0"?>';
echo "<results><item>PHP</item><item>MySQL</item></results>";Parse XML in JavaScript
fetch("/api/tags.xml")
.then((r) => r.text())
.then((xmlText) => {
const doc = new DOMParser().parseFromString(xmlText, "text/xml");
const items = doc.querySelectorAll("item");
items.forEach((el) => console.log(el.textContent));
});