Skip to content

AJAX Live Search

PHP Example: AJAX Live Search with Fetch API and JSON

Section titled “PHP Example: AJAX Live Search with Fetch API and JSON”

AJAX (Asynchronous JavaScript and XML - although JSON is now more common) allows web pages to request data from a server and update parts of the page without requiring a full reload. This creates faster, more interactive user experiences, like live search suggestions.

This example demonstrates a live search feature. As you type in the input field, JavaScript sends requests to a PHP script, which searches for matching data and returns suggestions in JSON format. The JavaScript then updates the page to display these suggestions.

Benefits of Live Search:

  • Immediate feedback: Results appear as the user types.
  • Refinement: Results narrow down with more characters.
  • Efficiency: Avoids unnecessary full page loads.

Imagine an input field and a div below it where results will appear:

<form onsubmit="return false;"> <!-- Prevent form submission -->
<label for="search">Search for a term:</label>
<input type="text" id="search" size="30" autocomplete="off">
</form>
<div id="livesearch-results" style="border: 1px solid #ccc; min-height: 20px; margin-top: 5px; padding: 5px;"></div>

The suggestions in this conceptual example would come from a PHP backend.

Example Explained - The Client-Side (JavaScript with Fetch)

Section titled “Example Explained - The Client-Side (JavaScript with Fetch)”

We use modern JavaScript (fetch API, async/await, addEventListener) to handle user input and communicate with the server.

<!-- Include this script block in your HTML page -->
<script>
document.addEventListener('DOMContentLoaded', () => {
const searchInput = document.getElementById('search');
const resultsContainer = document.getElementById('livesearch-results');
searchInput.addEventListener('keyup', async (event) => {
const query = event.target.value.trim();
if (query.length === 0) {
resultsContainer.innerHTML = '';
resultsContainer.style.display = 'none'; // Hide if empty
return;
}
try {
// Send request to the PHP backend
const response = await fetch(`livesearch.php?q=${encodeURIComponent(query)}`);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
// Expecting JSON response
const suggestions = await response.json();
// Update the results container
resultsContainer.style.display = 'block'; // Show results container
if (suggestions.length > 0) {
resultsContainer.innerHTML = ''; // Clear previous results
suggestions.forEach(suggestion => {
const div = document.createElement('div');
// Note: In a real app, link generation needs care
// Ensure suggestion.url is properly sanitized/validated if used directly
div.innerHTML = `<a href="#" onclick="alert('Selected: ${suggestion.title.replace(/'/g, "\\'")}')">${suggestion.title}</a>`;
resultsContainer.appendChild(div);
});
} else {
resultsContainer.innerHTML = 'No suggestions found.';
}
} catch (error) {
console.error('Error fetching search results:', error);
resultsContainer.innerHTML = 'Error loading suggestions.';
resultsContainer.style.display = 'block';
}
});
});
</script>

Code Explanation:

  • An event listener is attached to the input field’s keyup event.
  • If the input is empty, the results area is cleared and hidden.
  • The fetch API makes an asynchronous GET request to livesearch.php, passing the user’s query (q) as a URL parameter (properly encoded using encodeURIComponent).
  • async/await is used for cleaner handling of asynchronous operations.
  • Basic error handling checks the HTTP response status and catches network or JSON parsing errors.
  • The response is parsed as JSON using response.json().
  • The resultsContainer is dynamically updated with the suggestions received from the server, or a ‘no suggestions’ message.
  • Links are created for suggestions (in a real app, these would navigate or perform an action).

Example Explained - The Server-Side (PHP Script)

Section titled “Example Explained - The Server-Side (PHP Script)”

The livesearch.php script receives the search query, finds matching data (here, from a simple array), and returns the results as a JSON formatted string.

<?php
// Example data source (in a real app, this might come from a database)
$dataStore = [
['id' => 1, 'title' => 'HTML Tutorial', 'url' => '/html/'],
['id' => 2, 'title' => 'CSS Tutorial', 'url' => '/css/'],
['id' => 3, 'title' => 'JavaScript Tutorial', 'url' => '/js/'],
['id' => 4, 'title' => 'PHP Tutorial', 'url' => '/php/'],
['id' => 5, 'title' => 'SQL Introduction', 'url' => '/sql/'],
['id' => 6, 'title' => 'Python Basics', 'url' => '/python/']
];
// Get the search query parameter (with basic filtering)
$query = filter_input(INPUT_GET, 'q', FILTER_SANITIZE_STRING);
$suggestions = [];
if ($query && strlen($query) > 0) {
$queryLower = strtolower($query);
foreach ($dataStore as $item) {
// Case-insensitive search within the title
if (str_contains(strtolower($item['title']), $queryLower)) {
// Select only needed fields for the response
$suggestions[] = [
'title' => $item['title'],
'url' => $item['url'] // Ensure this is safe if used directly in JS!
];
}
// Limit the number of suggestions if needed
if (count($suggestions) >= 10) {
break;
}
}
}
// Set the content type header to JSON
header('Content-Type: application/json');
// Encode the suggestions array into JSON and output it
echo json_encode($suggestions);
?>

Code Explanation:

  • A simple array $dataStore acts as our database.
  • The search query q is retrieved from the GET request using filter_input for basic sanitization.
  • If a query exists, the code iterates through the data store.
  • str_contains (PHP 8+) performs a case-insensitive search (after converting both strings to lowercase). For older PHP, use stripos.
  • Matching items (only ‘title’ and ‘url’) are added to the $suggestions array.
  • The Content-Type header is set to application/json to inform the client.
  • json_encode() converts the PHP array into a JSON string, which is then sent back as the response.