JavaScript

JavaScript is a high-level, interpreted programming language that is widely used for web development. Initially designed as a client-side scripting language, it runs directly in web browsers, enabling dynamic and interactive user experiences. JavaScript can now be used for server-side development as well.

AJAX Database Example

15 April 2025 | Category:

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.