Lab 10: Live Search with AJAX
Additional Resources
Section titled “Additional Resources”- Adding Search and Filtering
- Working with the BaseModel class
- Lab 7: Implementing File Uploads
- Fetch API Documentation ↗
- URLSearchParams ↗
- JavaScript Event Handling ↗
- JSON in PHP ↗
Overview
Section titled “Overview”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:
- The user types in a search box, and JavaScript detects the input.
- JavaScript waits briefly (debouncing) to avoid sending a request on every keystroke.
- An AJAX request is sent to the backend with the search query and any filters.
- The backend queries the database and returns JSON results.
- JavaScript receives the data and updates the page without a full reload.
User Input > Debounce (300ms) > AJAX Request > Backend Query > JSON Response > DOM UpdateFor 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.
Learning Objectives
Section titled “Learning Objectives”By completing this lab, you will:
- Create an API endpoint that returns JSON data.
- Implement backend search logic using SQL
LIKEqueries andLEFT 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.
Prerequisites
Section titled “Prerequisites”Before starting this lab, ensure you have:
- Completed Lab 6 (
ProductsModel,ProductsController,findById(), andgetAllCategories()). - Completed Lab 7: Implementing File Uploads, which stores product images in the
product_imagestable and addsgetPrimaryImage(). - 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.
Part I: The Search API
Section titled “Part I: The Search API”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:
- Open
app/Domain/Models/ProductsModel.php - Add the following method:
/** * 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.}- Implement the TODOs
- 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_nameand: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 = 1condition goes in theONclause, not inWHERE. InWHERE, 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:
- Open
app/Controllers/ProductsController.php - Add
use App\Helpers\Core\JsonRenderer;at the top, and addprivate JsonRenderer $jsonRendererto the constructor, after theProductsModelparameter.JsonRenderercomes with the starter template: itsjson($response, $data)method encodes$dataas JSON, writes it to the response, and sets theContent-Type: application/jsonheader. - Add the following method:
/** * 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'.}- Implement the TODOs
- 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.
Step 3: Register the API Route
Section titled “Step 3: Register the API Route”Objective: Make the search endpoint reachable.
Instructions:
- Open
app/Routes/web-routes.php - Outside the
/admingroup, add:
$app->get('/api/products/search', [ProductsController::class, 'search']) ->setName('api.products.search');- Save the file
- Visit
http://localhost/your-app-name/api/products/search?q=ain your browser. You should see JSON listing the products whose name or description contains “a”.
Part II: The Public Products Pages
Section titled “Part II: The Public Products Pages”Step 4: Create the Public Products Page
Section titled “Step 4: Create the Public Products Page”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:
- Open
app/Controllers/ProductsController.phpand add the following method:
/** * 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'.}- Open
app/Routes/web-routes.phpand register the page outside the/admingroup:
$app->get('/products', [ProductsController::class, 'userIndex']) ->setName('products.public');- 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.
Step 5: Add a Placeholder Image
Section titled “Step 5: Add a Placeholder Image”Objective: Give products without an image something to display.
Instructions:
- In your
public/folder, create animages/folder - 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:
- Create the
app/Views/products/folder if it does not exist - Create a file named
userProductIndexView.phpinside it, with the following content:
<?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(); ?>- Save the file
- 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.
Step 7: Create the Product Details Page
Section titled “Step 7: Create the Product Details Page”Objective: Make the “View Details” links work.
Instructions:
- Add the following method to
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'.}- Register the route next to
/products:
$app->get('/products/{id:[0-9]+}', [ProductsController::class, 'userShow']) ->setName('products.public.show');- Create
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(); ?>- 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.
Part III: The Live Search (JavaScript)
Section titled “Part III: The Live Search (JavaScript)”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.
Step 8: Add the Debounce Function
Section titled “Step 8: Add the Debounce Function”Objective: Wait until the user stops typing before sending a request.
Add the following function to 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.
Step 9: Write the Fetch Function
Section titled “Step 9: Write the Fetch Function”Objective: Send the search to the API and return the products.
Instructions:
- Add the following code to
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);}- Implement the TODOs
- Save the file
Hints:
- Use
try/catcharound 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 checksresponse.ok. - Return
null, not an empty array, when the request fails. An empty array means “no products found”, which is a different message.
Step 10: Add the Rendering Functions
Section titled “Step 10: Add the Rendering Functions”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:
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:
- Add the following code to
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(); } });});- Implement the TODOs
- Save the file
Test Your Implementation
Section titled “Test Your Implementation”- Visit
/products. All products should appear, including those without an image (placeholder) or description. - 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.
- Type
lapin the search box and check that products matching “laptop” appear. - Search for a term and select a category to check that both filters combine.
- Type
zzzzzand check that “No products found matching your search.” appears. - Search for a word with an accent, such as
café, and check that it works. - Open the Network tab (F12), type
laptopquickly, and check that only one request is sent, about 300 ms after you stop typing. - Select a category without typing anything to check that the filter applies immediately.
- Type something, press Escape, and check that the search clears and all products appear.
- 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”.
Debugging with the Network Tab
Section titled “Debugging with the Network Tab”When working with AJAX, the browser’s Network tab is your primary debugging tool:
- Open Developer Tools (F12 or right-click and choose Inspect).
- Click the Network tab.
- Type in the search box to trigger an AJAX request.
- Look for requests to
/api/products/searchin the list. - 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. A404means the route is not registered or the URL is wrong. A500means there is a PHP error (check your Apache error logs). - The Response tab should show JSON with
success,count, andproductskeys. If you see HTML instead of JSON, a PHP error page is being returned. - The
Content-Typeheader should beapplication/json.
A 500 error with the message “Invalid parameter number” means the same placeholder appears twice in the query: check Step 1.
Security Considerations
Section titled “Security Considerations”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, useCONCAT('%', :search_name, '%')in the SQL and bind the parameter safely. - XSS is prevented on both sides:
hs()escapes output in PHP views, andescapeHtml()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.
Verification Checklist
Section titled “Verification Checklist”Before submitting your lab, verify the following:
-
/api/products/search?q=...returns JSON with theContent-Type: application/jsonheader - The search query uses two different placeholders for the name and the description
-
/productslists 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