Skip to content

AJAX PHP

AJAX (Asynchronous JavaScript and XML) allows web pages to communicate with a server in the background, without interfering with the display and behavior of the existing page. This enables dynamic updates and more interactive user experiences.

Although the ‘X’ originally stood for XML, modern AJAX often uses JSON (JavaScript Object Notation) for data exchange due to its ease of use with JavaScript.

This example demonstrates how a web page can fetch suggestions from a PHP script on the server as the user types into an input field, without requiring a full page reload.

<!-- Placeholder: Imagine an input field here -->
<label for="search">Start typing a name:</label>
<input type="text" id="search" name="search" onkeyup="showHint(this.value)">
<p>Suggestions: <span id="txtHint"></span></p>

As the user types in the input field, suggestions appear below.

Example Explained: The Frontend (HTML & JavaScript)

Section titled “Example Explained: The Frontend (HTML & JavaScript)”

When the user types a character (onkeyup event), the showHint() JavaScript function is called.

Modern JavaScript often uses the fetch API for making AJAX requests.

Here’s the updated HTML structure with JavaScript using fetch:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AJAX Search Suggestions</title>
<style>
#txtHint { color: green; }
.error { color: red; }
</style>
</head>
<body>
<h1>Live Search Example</h1>
<p>**Start typing a name in the input field below:**</p>
<form onsubmit="return false;"> <!-- Prevent form submission -->
<label for="search">First name:</label>
<input type="text" id="search" name="search" onkeyup="showHint(this.value)">
</form>
<p>Suggestions: <span id="txtHint"></span></p>
<script>
async function showHint(str) {
const hintElement = document.getElementById("txtHint");
if (str.length == 0) {
hintElement.innerHTML = "";
hintElement.className = ''; // Clear any error class
return;
}
try {
// Construct the URL for the PHP script, passing the input as a query parameter
const url = `gethint.php?q=${encodeURIComponent(str)}`;
// Use the fetch API to make the request
const response = await fetch(url);
// Check if the request was successful (status code 2xx)
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
// Get the response text
const data = await response.text();
// Update the hint element with the response
hintElement.innerHTML = data;
hintElement.className = ''; // Clear error class on success
} catch (error) {
console.error('Error fetching suggestions:', error);
hintElement.innerHTML = "Error fetching suggestions.";
hintElement.className = 'error'; // Add error class for styling
}
}
</script>
</body>
</html>

Code Explanation (JavaScript):

  • The showHint function is marked async to allow using await.
  • It checks if the input string (str) is empty; if so, clears the hint area and returns.
  • It constructs the url for the backend PHP script (gethint.php), appending the user’s input (str) as a URL-encoded query parameter q.
  • fetch(url) initiates an asynchronous HTTP GET request.
  • await response.ok checks if the HTTP status code indicates success (e.g., 200 OK).
  • await response.text() reads the response body as plain text.
  • The innerHTML of the txtHint span is updated with the received data.
  • A try...catch block handles potential network errors or issues during the fetch process.
  • encodeURIComponent() ensures the input string is safely included in the URL.
  • onsubmit="return false;" on the form prevents the default browser form submission behavior.

Example Explained: The Backend (PHP - gethint.php)

Section titled “Example Explained: The Backend (PHP - gethint.php)”

The PHP script receives the query parameter (q), searches a predefined list of names, and returns the matching suggestions as plain text (or potentially JSON for more complex data).

Here’s an improved gethint.php script:

<?php
// Array with names (using modern short array syntax)
$names = [
"Anna", "Amanda", "Amy",
"Brittany", "Bella",
"Cinderella", "Cindy", "Chloe",
"Diana", "Doris",
"Eva", "Eve", "Evita", "Elizabeth", "Ellen", "Emily",
"Fiona",
"Gunda", "Grace",
"Hege", "Hannah",
"Inga", "Isabella",
"Johanna", "Jessica",
"Kitty", "Kayla",
"Linda", "Liza", "Lily",
"Nina", "Natalie",
"Ophelia", "Olivia",
"Petunia", "Penelope",
"Raquel", "Riley",
"Sunniva", "Sophia", "Scarlett",
"Tove",
"Unni",
"Violet", "Vicky", "Victoria",
"Wenche", "Willow",
// Add more names as needed
];
// Get the 'q' query parameter from the URL
$query = $_GET["q"] ?? ''; // Use null coalescing operator for safety
$hint = "";
// Lookup suggestions only if the query is not empty
if ($query !== "") {
$queryLower = strtolower($query);
$len = strlen($queryLower);
$matches = [];
foreach ($names as $name) {
// Check if the beginning of the name matches the query (case-insensitive)
if (strncasecmp($queryLower, $name, $len) === 0) {
$matches[] = htmlspecialchars($name); // Sanitize output
}
}
// Format the hint string
if (!empty($matches)) {
$hint = implode(", ", $matches);
} else {
$hint = "no suggestion";
}
}
// Output the hint string (or "no suggestion")
// Set content type if needed (though text/html is often default)
// header('Content-Type: text/plain');
echo $hint;
?>

Code Explanation (PHP):

  • Uses modern short array syntax [].
  • Safely gets the query parameter q using $_GET["q"] ?? ''.
  • Converts the query to lowercase (strtolower) for case-insensitive comparison.
  • Iterates through the $names array using foreach.
  • Uses strncasecmp() for efficient, case-insensitive comparison of the beginning of strings.
  • Collects matching names in the $matches array.
  • Uses htmlspecialchars() on each match before adding it to the array to prevent potential XSS issues if names contained special characters.
  • implode(", ", $matches) joins the found names into a comma-separated string.
  • Outputs the resulting string or “no suggestion”.
  • Consider setting a Content-Type header (e.g., text/plain or application/json if returning JSON) for clarity, although browsers often handle plain text correctly.

This AJAX pattern is fundamental for creating responsive web applications that update parts of the page dynamically based on user interaction or server events.