40 | P a g e
Create a PHP script to process the AJAX request and return matching records from
the database.
6) Display Results
7) Update the HTML to display the search results dynamically.
Example
Database Creation and Sample Data (MySQL)
CREATE DATABASE school;
USE school;
CREATE TABLE students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
age INT,
grade VARCHAR(10),
email VARCHAR(100)
);
INSERT INTO students (name, age, grade, email) VALUES
('Alice Johnson', 20, 'A', '
[email protected]'),
('Bob Smith', 22, 'B', '
[email protected]'),
('Charlie Brown', 21, 'C', '
[email protected]'),
('David Wilson', 23, 'A', '
[email protected]');
HTML Form and AJAX Script
<!DOCTYPE html>
<html>
<head>
<title>AJAX Student Search</title>
<script>
function searchStudent() {
var query = document.getElementById('search').value;
var xhr = new XMLHttpRequest();
xhr.open('GET', 'search.php?query=' + query, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById('results').innerHTML = xhr.responseText;
}
};
xhr.send();
}
</script>
</head>
<body>
<h1>Search Student Records</h1>
<input type="text" id="search" onkeyup="searchStudent()" placeholder="Search by name...">
<div id="results"></div>
</body>
</html>