Load Customer Details with AJAX and PHP

Request one customer and return JSON

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;
Current practice: keep client-side validation for user experience, but always repeat validation on the server. For database input, use PDO or MySQLi prepared statements.

The complete browser example below uses the same Fetch request and POST contract as the live demo.

We can enter the customer id or any student number in one input field and get back the full details of the customer. User enters a number as customer id and the JavaScript function getInfo() gets trigger by onBlur event handler of the textbox. We have used onBlur but any other event handler can be used, a button can be used with onClick event handler.

You can understand this requirement can be easily done by using one web form and submitting the data to a server side script. But by using Ajax we need not submit the form and load a new page. The same page can collect the information in the background with the Fetch API and display the returned data without reloading the page.

Here is the demo. Please use customer id 3, 5 or 7 to get the name of the customer for any other id you will get message saying No customer name available.

Demo of Record details by PHP Ajax
For a comparison with the lower-level XMLHttpRequest API, see the dedicated tutorial.

Usually the data is taken from a customer table but for simplicity we have kept an array here with three customer details. This server side part can be extended to connect a database and details of customer can be collected. This part of the code we kept in a PHP script ( code.php file ) and you can easily modify this small script. The small PHP code is here.


$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.

Let us look at the JavaScript and Ajax part.

The getInfo() function runs when the user leaves the customer ID field. It places the ID in 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.

Here is the complete HTML page using the same Fetch request as the live demo.
<!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 )
Ajax Json XML


Subscribe to our YouTube Channel here



plus2net.com











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