AJAXÂ Database Example
15 April 2025 | Category: JavaScript
This tutorial demonstrates how to use AJAX to fetch data from a MySQL database without reloading the page.
đ§ What We’ll Build
A search box that retrieves user data from a database using AJAX as you type.
đ Project Structure
ajax-database/
â
âââ index.html â Frontend with AJAX
âââ search.php â PHP backend script
âââ db.php â Database connection file
đ§ą 1. Create Database and Table
CREATE DATABASE ajax_demo;
USE ajax_demo;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100)
);
INSERT INTO users (name, email) VALUES
('John Doe', 'john@example.com'),
('Jane Smith', 'jane@example.com'),
('Alice Johnson', 'alice@example.com');
đ 2. db.php
â Database Connection
<?php
$host = "localhost";
$user = "root";
$password = "";
$db = "ajax_demo";
$conn = new mysqli($host, $user, $password, $db);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
đ 3. search.php
â Fetch Matching Records
<?php
include 'db.php';
if (isset($_GET['query'])) {
$search = $conn->real_escape_string($_GET['query']);
$sql = "SELECT * FROM users WHERE name LIKE '%$search%' OR email LIKE '%$search%'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "<p><strong>" . $row['name'] . "</strong> - " . $row['email'] . "</p>";
}
} else {
echo "<p>No users found.</p>";
}
}
?>
đĽď¸ 4. index.html
â Search with AJAX
<!DOCTYPE html>
<html>
<head>
<title>AJAX Database Search</title>
</head>
<body>
<h2>Live User Search</h2>
<input type="text" id="search" placeholder="Type name or email">
<div id="results"></div>
<script>
document.getElementById('search').addEventListener('keyup', function () {
const query = this.value;
const xhr = new XMLHttpRequest();
xhr.open("GET", "search.php?query=" + encodeURIComponent(query), true);
xhr.onload = function () {
if (xhr.status === 200) {
document.getElementById("results").innerHTML = xhr.responseText;
}
};
xhr.send();
});
</script>
</body>
</html>
đ§ Summary
- The user types in the input field.
- JavaScript captures the input and sends it to
search.php
using AJAX. - PHP searches the MySQL database and returns matching records.
- The results are displayed in real time without reloading the page.
đ ď¸ Tips
- Always sanitize inputs (
$conn->real_escape_string
) to prevent SQL injection. - Use Prepared Statements for better security in production apps.
- You can easily convert this to use JSON instead of raw HTML.