A predictable JSON response keeps the browser code simple. Validate the customer ID and use a prepared statement before reading the record.
const customerId = document.getElementById('customer_id').value;
const body = new URLSearchParams({ customer_id: customerId });
const response = await fetch('ajax-customer-code.php', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body
});
const message = await response.text();
document.getElementById('txtHint').textContent = message;The complete browser example below uses the same Fetch request and POST contract as the live demo.
$customerId = filter_input(INPUT_POST, 'customer_id', FILTER_VALIDATE_INT);
$customers = [3 => 'Jim', 5 => 'Ron', 7 => 'Kim'];
if ($customerId !== false && $customerId !== null && array_key_exists($customerId, $customers)) {
echo 'Name of the customer: ' . $customers[$customerId];
} else {
echo 'No customer name available';
}
As you can see in the above code, the script collects the customer_id and then if the id is present inside the (PHP) array then the name of the corresponding customer is returned, otherwise a message saying customer name not there is returned to calling html page. We used array_key_exists() to search for the customer id.
URLSearchParams, sends it by POST with fetch(), checks the HTTP response, and writes the returned text into the txtHint element. No page reload is required.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Customer lookup</title>
</head>
<body>
<form id="customer-form">
Customer ID:
<input type="number" id="customer_id" name="customer_id" min="1">
</form>
<div id="txtHint">Customer info will be listed here.</div>
<script>
async function getInfo() {
const customerId = document.getElementById('customer_id').value;
const body = new URLSearchParams({ customer_id: customerId });
try {
const response = await fetch('ajax-customer-code.php', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
body
});
const message = await response.text();
if (!response.ok) {
throw new Error(message || 'Lookup failed.');
}
document.getElementById('txtHint').textContent = message;
} catch (error) {
document.getElementById('txtHint').textContent = error.message;
}
}
document.getElementById('customer_id').addEventListener('blur', getInfo);
</script>
</body>
</html>
Download the zip file ( both code.htm & code.php )
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.