Skip to content

Lab 10: Live Search with AJAX

In this lab, you will build the public products page of your store and add a live search that filters products as users type. This pattern, also called “search-as-you-type”, needs no “Search” button and gives instant feedback.

Live search is used on platforms like Amazon, eBay, and social media sites. The process works as follows:

  1. The user types in a search box, and JavaScript detects the input.
  2. JavaScript waits briefly (debouncing) to avoid sending a request on every keystroke.
  3. An AJAX request is sent to the backend with the search query and any filters.
  4. The backend queries the database and returns JSON results.
  5. JavaScript receives the data and updates the page without a full reload.
User Input > Debounce (300ms) > AJAX Request > Backend Query > JSON Response > DOM Update

For example, when a user types "lap", the browser sends GET /api/products/search?q=lap&category=1 to the server. The server queries the database using a LIKE clause, formats the matching products as JSON, and returns them. JavaScript then renders the results as product cards on the page.


By completing this lab, you will:

  • Create an API endpoint that returns JSON data.
  • Implement backend search logic using SQL LIKE queries and LEFT JOINs.
  • Send AJAX requests with the Fetch API and build query strings with URLSearchParams.
  • Implement debouncing to reduce the number of requests sent to the server.
  • Update the DOM from server responses, and ignore responses that arrive out of order.
  • Handle loading states, errors, and empty results.

Before starting this lab, ensure you have:

  • Completed Lab 6 (ProductsModel, ProductsController, findById(), and getAllCategories()).
  • Completed Lab 7: Implementing File Uploads, which stores product images in the product_images table and adds getPrimaryImage().
  • Some products in the database, with a few images uploaded and at least one product without a description.
  • Basic knowledge of JavaScript (variables, functions, arrays, objects) and the JSON format.

Step 1: Add the Search Method to the ProductsModel

Section titled “Step 1: Add the Search Method to the ProductsModel”

Objective: Write a query that finds products by name or description, optionally in one category.

Instructions:

  1. Open app/Domain/Models/ProductsModel.php
  2. Add the following method:
app/Domain/Models/ProductsModel.php
/**
* Return the products whose name or description contains $searchTerm,
* optionally limited to one category.
*/
public function searchProducts(string $searchTerm = '', ?int $categoryId = null): array
{
// TODO: 1. Build the base query:
// - FROM products p
// - LEFT JOIN categories c ON p.category_id = c.id
// - LEFT JOIN product_images pi ON p.id = pi.product_id AND pi.is_primary = 1
// - Select: p.id, p.name, p.description, p.price, p.stock_quantity,
// c.name AS category_name, c.id AS category_id, pi.file_path AS image_path
// - End with WHERE 1=1, so every filter below can start with AND
// TODO: 2. If $searchTerm is not empty, add this condition and its two parameters:
// AND (p.name LIKE CONCAT('%', :search_name, '%')
// OR p.description LIKE CONCAT('%', :search_desc, '%'))
// TODO: 3. If $categoryId is greater than 0, add AND p.category_id = :category_id
// TODO: 4. Sort by p.name and return all matching rows.
}
  1. Implement the TODOs
  2. Save the file

Hints:

  • Collect the parameters in an array as you add each condition, then pass both the SQL and the array to the BaseModel method that returns all rows.
  • The search term is bound twice, under two different names (:search_name and :search_desc). With the database settings of your project, PDO does not allow the same placeholder to appear twice in one query.
  • The is_primary = 1 condition goes in the ON clause, not in WHERE. In WHERE, it would remove every product that has no image.
  • Each product has at most one primary image (Lab 7), so the join never returns a product twice.

Step 2: Add the Search Endpoint to the ProductsController

Section titled “Step 2: Add the Search Endpoint to the ProductsController”

Objective: Return the search results as JSON.

Instructions:

  1. Open app/Controllers/ProductsController.php
  2. Add use App\Helpers\Core\JsonRenderer; at the top, and add private JsonRenderer $jsonRenderer to the constructor, after the ProductsModel parameter. JsonRenderer comes with the starter template: its json($response, $data) method encodes $data as JSON, writes it to the response, and sets the Content-Type: application/json header.
  3. Add the following method:
app/Controllers/ProductsController.php
/**
* Search products (GET /api/products/search?q=...&category=...).
*/
public function search(Request $request, Response $response, array $args): Response
{
// TODO: 1. Read the 'q' and 'category' query parameters.
// - q: trimmed, or an empty string if missing
// - category: an int if present, otherwise null
// TODO: 2. If the search term is longer than 100 characters, keep only the
// first 100 (see the hint).
// TODO: 3. Search the products with the model method from Step 1.
// TODO: 4. Return a JSON response with the keys:
// 'success' => true, 'count', 'query', 'category_id', and 'products'.
}
  1. Implement the TODOs
  2. Save the file

Hints:

  • substr() counts bytes, so it can cut an accented character such as é in half. mb_substr() counts characters.
  • JsonRenderer::json() leaves the status code at 200, which is what a successful search returns.

Objective: Make the search endpoint reachable.

Instructions:

  1. Open app/Routes/web-routes.php
  2. Outside the /admin group, add:
app/Routes/web-routes.php
$app->get('/api/products/search', [ProductsController::class, 'search'])
->setName('api.products.search');
  1. Save the file
  2. Visit http://localhost/your-app-name/api/products/search?q=a in your browser. You should see JSON listing the products whose name or description contains “a”.

Objective: Add the customer-facing page that lists all products. The admin product list from Lab 5 stays under /admin; this page is for visitors.

Instructions:

  1. Open app/Controllers/ProductsController.php and add the following method:
app/Controllers/ProductsController.php
/**
* Display the public product list (GET /products).
*/
public function userIndex(Request $request, Response $response, array $args): Response
{
// TODO: 1. Get all products with their category name and primary image.
// searchProducts() from Step 1, called without a search term or
// category, returns exactly that.
// TODO: 2. Get all categories for the filter dropdown (getAllCategories()
// from Lab 5 already does this).
// TODO: 3. Render 'products/userProductIndexView.php' with the keys
// 'title' => 'Products', 'products', and 'categories'.
}
  1. Open app/Routes/web-routes.php and register the page outside the /admin group:
app/Routes/web-routes.php
$app->get('/products', [ProductsController::class, 'userIndex'])
->setName('products.public');
  1. Save both files

You will create the view in Step 6. getAll() from Lab 5 is not used here because it returns neither the category name nor the image path that the product cards display.


Objective: Give products without an image something to display.

Instructions:

  1. In your public/ folder, create an images/ folder
  2. Save any small image (for example, a grey square with the text “No image”) in it as placeholder.jpg

The views and the JavaScript display public/images/placeholder.jpg for every product whose image_path is empty. Without this file, those products show a broken image.


Step 6: Create the Products View with the Search UI

Section titled “Step 6: Create the Products View with the Search UI”

Objective: Display the products as cards, with a search box and a category filter above them.

Instructions:

  1. Create the app/Views/products/ folder if it does not exist
  2. Create a file named userProductIndexView.php inside it, with the following content:
app/Views/products/userProductIndexView.php
<?php
use App\Helpers\ViewHelper;
ViewHelper::loadHeader($title);
?>
<div class="container my-4">
<h1 class="mb-4">Browse Products</h1>
<!-- Search and Filter Section -->
<div class="row mb-4">
<div class="col-md-8">
<label for="searchInput" class="visually-hidden">Search products</label>
<input
type="search"
class="form-control"
id="searchInput"
placeholder="Search products by name or description..."
>
</div>
<div class="col-md-3">
<label for="categoryFilter" class="visually-hidden">Filter by category</label>
<select class="form-select" id="categoryFilter">
<option value="">All Categories</option>
<?php foreach ($categories as $category): ?>
<option value="<?= hs($category['id']) ?>">
<?= hs($category['name']) ?>
</option>
<?php endforeach; ?>
</select>
</div>
<div class="col-md-1">
<div id="loadingSpinner" class="spinner-border text-primary" role="status" style="display: none;">
<span class="visually-hidden">Loading...</span>
</div>
</div>
</div>
<!-- Search Results (filled by JavaScript; screen readers announce changes) -->
<div id="searchResults" class="row" aria-live="polite"></div>
<!-- Default Products Display (shown until the first search) -->
<div id="defaultProducts" class="row">
<?php foreach ($products as $product): ?>
<?php $description = $product['description'] ?? ''; ?>
<div class="col-md-4 mb-4">
<div class="card h-100">
<img
src="<?= APP_BASE_URL ?>/public/<?= hs($product['image_path'] ?? 'images/placeholder.jpg') ?>"
class="card-img-top"
alt="<?= hs($product['name']) ?>"
style="height: 200px; object-fit: cover;"
>
<div class="card-body">
<h5 class="card-title"><?= hs($product['name']) ?></h5>
<p class="card-text"><?= hs(mb_strimwidth($description, 0, 100, '...')) ?></p>
<p class="fw-bold text-success">$<?= hs(number_format((float) $product['price'], 2)) ?></p>
<span class="badge bg-secondary"><?= hs($product['category_name'] ?? 'Uncategorized') ?></span>
</div>
<div class="card-footer">
<a href="<?= APP_BASE_URL ?>/products/<?= hs($product['id']) ?>" class="btn btn-primary btn-sm">View Details</a>
</div>
</div>
</div>
<?php endforeach; ?>
</div>
</div>
<!-- Pass the base URL to JavaScript -->
<script>
window.APP_BASE_URL = '<?= APP_BASE_URL ?>';
</script>
<script src="<?= APP_BASE_URL ?>/public/js/product-search.js"></script>
<?php ViewHelper::loadFooter(); ?>
  1. Save the file
  2. Visit http://localhost/your-app-name/products. All products should be displayed, and the category dropdown should list your categories.

The window.APP_BASE_URL variable gives JavaScript the same base URL as PHP, so requests work when the application runs in a subfolder. mb_strimwidth() shortens the description to 100 characters and adds ”…” only when it was longer; the ?? '' handles products without a description.


Objective: Make the “View Details” links work.

Instructions:

  1. Add the following method to ProductsController.php:
app/Controllers/ProductsController.php
/**
* Display one product (GET /products/{id}).
*/
public function userShow(Request $request, Response $response, array $args): Response
{
// TODO: 1. Fetch the product whose ID is in the route arguments (findById() from Lab 6).
// If it does not exist, set an error flash message using the FlashMessage
// helper class and redirect to 'products.public'.
// TODO: 2. Get its primary image path (getPrimaryImage() from Lab 7).
// TODO: 3. Render 'products/userProductShowView.php' with the keys
// 'title' (the product's name), 'product', and 'image'.
}
  1. Register the route next to /products:
app/Routes/web-routes.php
$app->get('/products/{id:[0-9]+}', [ProductsController::class, 'userShow'])
->setName('products.public.show');
  1. Create app/Views/products/userProductShowView.php:
app/Views/products/userProductShowView.php
<?php
use App\Helpers\ViewHelper;
ViewHelper::loadHeader($title);
?>
<div class="container my-4">
<div class="row">
<div class="col-md-5">
<img
src="<?= APP_BASE_URL ?>/public/<?= hs($image ?? 'images/placeholder.jpg') ?>"
class="img-fluid rounded"
alt="<?= hs($product['name']) ?>"
>
</div>
<div class="col-md-7">
<h1><?= hs($product['name']) ?></h1>
<p class="fs-4 fw-bold text-success">$<?= hs(number_format((float) $product['price'], 2)) ?></p>
<p><?= nl2br(hs($product['description'] ?? '')) ?></p>
<p class="text-muted">In stock: <?= hs($product['stock_quantity']) ?></p>
<a href="<?= APP_BASE_URL ?>/products" class="btn btn-outline-secondary">Back to Products</a>
</div>
</div>
</div>
<?php ViewHelper::loadFooter(); ?>
  1. Save the files

The {id:[0-9]+} pattern only matches numbers, so a URL such as /products/abc gives a 404 instead of reaching the controller.


All the code in this part goes in one file: public/js/product-search.js. Create the public/js/ folder if it does not exist.

Objective: Wait until the user stops typing before sending a request.

Add the following function to public/js/product-search.js:

public/js/product-search.js
function debounce(func, delay) {
let timeoutId;
return function (...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => func.apply(this, args), delay);
};
}

debounce() returns a new function. Each call restarts a timer, and func only runs once no call has happened for delay milliseconds. Typing “laptop” quickly therefore sends one request instead of six.


Objective: Send the search to the API and return the products.

Instructions:

  1. Add the following code to public/js/product-search.js:
public/js/product-search.js
/**
* Fetch the products matching the search term and category.
* Returns an array of products, or null if the request failed.
*/
async function fetchProducts(searchTerm, categoryId) {
// TODO: 1. Build the query string with URLSearchParams: add 'q' only if
// searchTerm is not empty, and 'category' only if categoryId is not empty.
// TODO: 2. Send a GET request to `${window.APP_BASE_URL}/api/products/search?...`
// with fetch().
// TODO: 3. If the response is not OK (response.ok is false), or the request
// throws an error: log the error with console.error(), show the message
// "Failed to load products. Please try again." with showError(), and
// return null.
// TODO: 4. Otherwise, parse the JSON and return its products array.
}
function showError(message) {
const container = document.getElementById('searchResults');
container.textContent = '';
const alert = document.createElement('div');
alert.className = 'col-12';
alert.innerHTML = '<div class="alert alert-danger" role="alert"></div>';
alert.firstChild.textContent = message;
container.appendChild(alert);
}
  1. Implement the TODOs
  2. Save the file

Hints:

  • Use try/catch around the request: fetch() throws when the server cannot be reached, but not when it answers with an error status such as 404 or 500. That is why step 3 also checks response.ok.
  • Return null, not an empty array, when the request fails. An empty array means “no products found”, which is a different message.

Objective: Turn the products returned by the API into cards.

Add the following functions to public/js/product-search.js. renderProducts() hides the cards rendered by PHP and replaces them with new ones. escapeHtml() prevents XSS by converting special characters to HTML entities before they are inserted into the page:

public/js/product-search.js
function renderProducts(products) {
const resultsContainer = document.getElementById('searchResults');
const defaultContainer = document.getElementById('defaultProducts');
if (defaultContainer) defaultContainer.style.display = 'none';
resultsContainer.textContent = '';
if (products.length === 0) {
const alert = document.createElement('div');
alert.className = 'col-12';
alert.innerHTML = '<div class="alert alert-info" role="alert">No products found matching your search.</div>';
resultsContainer.appendChild(alert);
return;
}
products.forEach(product => {
resultsContainer.appendChild(createProductCard(product));
});
}
function createProductCard(product) {
const col = document.createElement('div');
col.className = 'col-md-4 mb-4';
const fullDescription = product.description || '';
const description = fullDescription.length > 100
? fullDescription.substring(0, 100) + '...'
: fullDescription;
col.innerHTML = `
<div class="card h-100">
<img
src="${window.APP_BASE_URL}/public/${escapeHtml(product.image_path || 'images/placeholder.jpg')}"
class="card-img-top"
alt="${escapeHtml(product.name)}"
style="height: 200px; object-fit: cover;"
>
<div class="card-body">
<h5 class="card-title">${escapeHtml(product.name)}</h5>
<p class="card-text">${escapeHtml(description)}</p>
<p class="fw-bold text-success">$${parseFloat(product.price).toFixed(2)}</p>
<span class="badge bg-secondary">${escapeHtml(product.category_name || 'Uncategorized')}</span>
</div>
<div class="card-footer">
<a href="${escapeHtml(window.APP_BASE_URL)}/products/${escapeHtml(String(product.id))}" class="btn btn-primary btn-sm">View Details</a>
</div>
</div>
`;
return col;
}
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}

product.description || '' handles products without a description: the API returns null for them, and null.length would stop the script with a TypeError.


Step 11: Connect the Search Box and the Filter

Section titled “Step 11: Connect the Search Box and the Filter”

Objective: Run a search when the user types or changes the category, and display only the latest results.

Instructions:

  1. Add the following code to public/js/product-search.js:
public/js/product-search.js
document.addEventListener('DOMContentLoaded', function () {
const searchInput = document.getElementById('searchInput');
const categoryFilter = document.getElementById('categoryFilter');
const loadingSpinner = document.getElementById('loadingSpinner');
// Number of the most recent search; used to ignore older responses.
let latestRequest = 0;
async function performSearch() {
// TODO: 1. Add 1 to latestRequest and remember this search's number
// in a local constant.
// TODO: 2. Show the spinner, then fetch the products for the trimmed
// search term and the selected category.
// TODO: 3. If a newer search started while this one was waiting
// (its number is no longer latestRequest), stop here
// without changing the page.
// TODO: 4. Hide the spinner. If the request failed (null), stop:
// fetchProducts() already displayed the error.
// Otherwise, render the products.
}
const debouncedSearch = debounce(performSearch, 300);
searchInput.addEventListener('input', debouncedSearch);
categoryFilter.addEventListener('change', performSearch);
searchInput.addEventListener('keydown', function (e) {
if (e.key === 'Escape') {
searchInput.value = '';
categoryFilter.value = '';
performSearch();
}
});
});
  1. Implement the TODOs
  2. Save the file

  1. Visit /products. All products should appear, including those without an image (placeholder) or description.
  2. Click “View Details” on a product. Its details page should open. Change the ID in the URL to one that does not exist: you should be back on the list with an error message.
  3. Type lap in the search box and check that products matching “laptop” appear.
  4. Search for a term and select a category to check that both filters combine.
  5. Type zzzzz and check that “No products found matching your search.” appears.
  6. Search for a word with an accent, such as café, and check that it works.
  7. Open the Network tab (F12), type laptop quickly, and check that only one request is sent, about 300 ms after you stop typing.
  8. Select a category without typing anything to check that the filter applies immediately.
  9. Type something, press Escape, and check that the search clears and all products appear.
  10. Stop the database server (or rename the API route temporarily) and search. “Failed to load products. Please try again.” should appear, not “No products found”.

When working with AJAX, the browser’s Network tab is your primary debugging tool:

  1. Open Developer Tools (F12 or right-click and choose Inspect).
  2. Click the Network tab.
  3. Type in the search box to trigger an AJAX request.
  4. Look for requests to /api/products/search in the list.
  5. Click on a request to inspect it.

Check the following:

  • The request URL should be http://localhost/your-app-name/api/products/search?q=yourterm&category=1.
  • The status code should be 200 OK. A 404 means the route is not registered or the URL is wrong. A 500 means there is a PHP error (check your Apache error logs).
  • The Response tab should show JSON with success, count, and products keys. If you see HTML instead of JSON, a PHP error page is being returned.
  • The Content-Type header should be application/json.

A 500 error with the message “Invalid parameter number” means the same placeholder appears twice in the query: check Step 1.


Several security practices are built into this implementation:

  • SQL injection is prevented by using prepared statements with named parameters. Never concatenate user input directly into SQL like "WHERE name LIKE '%$searchTerm%'". Instead, use CONCAT('%', :search_name, '%') in the SQL and bind the parameter safely.
  • XSS is prevented on both sides: hs() escapes output in PHP views, and escapeHtml() escapes output in JavaScript before inserting it into the DOM.
  • The search term is limited to 100 characters, and the category is converted to an integer.
  • % and _ keep their special meaning inside the bound value: _ matches any single character and % any sequence. Typing % therefore matches every product. This is not a security risk, because the value is still bound as data, but it can return more results than expected.

Before submitting your lab, verify the following:

  • /api/products/search?q=... returns JSON with the Content-Type: application/json header
  • The search query uses two different placeholders for the name and the description
  • /products lists all products, with a placeholder for products without an image
  • “View Details” opens the product’s page, and an unknown ID returns to the list with an error
  • Typing sends one request after a 300 ms pause, not one per key
  • Results from an older request never replace newer ones
  • A failed request shows an error message, not “No products found”
  • Products without a description display without errors