AJAX (Asynchronous JavaScript and XML) allows you to fetch data from a server without having to reload the whole page. Combined with PHP, you can create a dynamic "live search" experience, where results from the server are fetched and displayed in real-time as the user types. Let's break it down step by step:
First, create an input field where the user can type their query:
<input type="text" id="searchQuery" onkeyup="showResults(this.value)" placeholder="Search for names...">
When a user types in the search field, we'll use AJAX to get the data from the server:
function showResults(query) {
if (query.length == 0) {
document.getElementById("liveSearchResults").innerHTML = "";
return;
}
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("liveSearchResults").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "getResults.php?q=" + query, true);
xmlhttp.send();
}
Here's a basic example of a PHP script that fetches results from a database:
<?php
$host = "localhost";
$dbname = "mydb";
$username = "username";
$password = "password";
$connection = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = $_GET["q"];
$stmt = $connection->prepare("SELECT name FROM users WHERE name LIKE :query LIMIT 10");
$stmt->bindValue(":query", "%$query%");
$stmt->execute();
$results = $stmt->fetchAll();
foreach ($results as $row) {
echo $row['name'] . "<br>";
}
?>
This example assumes you have a MySQL database with a table called `users` and a column named `name`. Adjust the database and query as needed.
For a better user experience, consider adding some CSS to style the search results:
#liveSearchResults {
border: 1px solid #A0A0A0;
max-height: 150px;
overflow-y: auto;
}
#liveSearchResults div {
padding: 10px;
cursor: pointer;
}
#liveSearchResults div:hover {
background-color: #f1f1f1;
}
Implementing a PHP AJAX live search requires knowledge in both frontend (JavaScript) and backend (PHP) development. Ensure your solution is robust, secure, and provides a smooth user experience.
UPCET Exam
Click Here
SAAT Exam
Click Here
MHT CET Exam
Click Here
IPU CET Exam
Click Here
KCET Exam
Click Here
COMEDK UG Exam
Click Here
VITEEE Exam
Click Here
BITSAT
Click Here
DSAT: Dayanand Sagar Admission Test
Click Here
Career In Animation in india
Click Here
Merchant Navy Courses in india
Click Here
Interior Design Career in india
Click Here
UGC NET Exam
Click Here
B. Ed Exam
Click Here
AFCAT - Air Force Common Admission Test
Click Here
GATE Exam
Click Here
Joint Entrance Examination (JEE)
Click Here
Common Admission Test (CAT)
Click Here
CDS - Combined Defence Services Exam
Click Here