
AJAX Search Example
Sure! Below is a simple example of an AJAX search feature using HTML, JavaScript (with XMLHttpRequest), and PHP on the server-side.
HTML (index.html):
<!DOCTYPE html>
<html>
<head>
<title>AJAX Search Example</title>
<script src="script.js"></script>
</head>
<body>
<h1>Search Example</h1>
<input type="text" id="searchInput" onkeyup="performSearch()">
<div id="searchResults"></div>
</body>
</html>
JavaScript (script.js):
function performSearch() {
var searchTerm = document.getElementById("searchInput").value;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
displayResults(response);
} else {
console.error("Error: " + xhr.status);
}
}
};
xhr.open("GET", "search.php?q=" + encodeURIComponent(searchTerm), true);
xhr.send();
}
function displayResults(results) {
var searchResultsDiv = document.getElementById("searchResults");
searchResultsDiv.innerHTML = "";
if (results.length === 0) {
searchResultsDiv.innerHTML = "<p>No results found.</p>";
} else {
var ul = document.createElement("ul");
results.forEach(function (result) {
var li = document.createElement("li");
li.textContent = result;
ul.appendChild(li);
});
searchResultsDiv.appendChild(ul);
}
}
PHP (search.php):
<?php
// Simulated search results
$database = array(
"apple",
"banana",
"orange",
"grape",
"pineapple",
"kiwi",
"mango",
"watermelon",
"strawberry",
"blueberry"
);
$searchTerm = $_GET["q"];
$results = array();
foreach ($database as $item) {
if (stripos($item, $searchTerm) !== false) {
$results[] = $item;
}
}
header("Content-Type: application/json");
echo json_encode($results);
?>
In this example, the HTML file contains an input field where users can type their search term. When the user types, the performSearch()
function is called, which initiates an AJAX request to the server (search.php) with the search term as a query parameter.
The PHP script (search.php) receives the search term, simulates a database search, and returns the matching results in JSON format.
Back on the client-side, the displayResults()
function processes the JSON response and updates the searchResultsDiv with the list of search results.
Please note that this is a basic example for illustrative purposes. In real-world scenarios, you would typically have a more sophisticated backend with a real database or API to handle the search requests and return meaningful results. Also, consider implementing proper error handling and security measures to prevent vulnerabilities like SQL injection when building production-grade applications.