Implementing AJAX Live Search with PHP and MySQL
Last Updated :
21 Aug, 2024
AJAX (Asynchronous JavaScript and XML) is a technique used to create dynamic web applications. It allows web pages to be updated asynchronously by exchanging data with a web server behind the scenes. This means that web pages can be updated without requiring a full page reload. AJAX Live Search is a feature that provides real-time search results as users type in a search box. This improves user experience by allowing instant feedback and suggestions. The following steps will guide you through implementing an AJAX live search using PHP and MySQL
Prerequisite
Steps to Create PHP Application Using MySQL Database for AJAX Search
Step 1: Create the Database
Create a new MySQL database named test_db to store your data.
CREATE DATABASE test_db;
Step 2: Create the Table
Within the test_db database, create a table named users to hold user names.
USE test_db;
CREATE TABLE users (
id INT(11) AUTO_INCREMENT PRIMARY KEY,
user_name VARCHAR(255) NOT NULL
);
Step 3: Insert Sample Data
Add sample data to the users table for testing purposes.
INSERT INTO users (user_name) VALUES ('Alice Johnson');
INSERT INTO users (user_name) VALUES ('Bob Smith');
INSERT INTO users (user_name) VALUES ('Charlie Brown');
INSERT INTO users (user_name) VALUES ('David Wilson');
INSERT INTO users (user_name) VALUES ('Emily Davis');
Step 4: Create Project Files
Create the necessary files for your project. The file structure will look like this:
project structureNote: Place the live-search directory in the htdocs folder of XAMPP or the equivalent directory for your local server.
Step 5: Create HTML File
This HTML file includes a search input and a table to display the results. It uses jQuery to handle the search functionality. Initially, all records are loaded into the table, and as the user types in the search box, AJAX requests fetch matching results from the server.
HTML
<!-- live-search/index.html --->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AJAX Live Search</title>
<link rel="stylesheet" href="style.css">
<script src=
"https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h1>User List</h1>
<input type="text" id="search" placeholder="Search...">
<table id="result">
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
<tbody>
<!-- Initial data will be loaded here -->
</tbody>
</table>
<script>
$(document).ready(function () {
// Load all records initially
loadAllRecords();
// Perform search
$('#search').on('keyup', function () {
var query = $(this).val();
if (query.length > 2) {
$.ajax({
url: 'search.php',
type: 'POST',
data: { search: query },
success: function (data) {
$('#result tbody').html(data);
}
});
} else {
loadAllRecords();
}
});
function loadAllRecords() {
$.ajax({
url: 'search.php',
type: 'POST',
data: { search: '' },
success: function (data) {
$('#result tbody').html(data);
}
});
}
});
</script>
</body>
</html>
Step 6: Create PHP File
This PHP script handles the AJAX requests and retrieves data from the MySQL database based on the search query. This PHP script connects to the MySQL database, retrieves records based on the search query, and returns the results as HTML table rows. If no search query is provided, it returns all records.
PHP
//live-search/search.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test_db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST['search'])) {
$search = $conn->real_escape_string($_POST['search']);
$sql = $search ?
"SELECT user_name FROM users WHERE user_name LIKE '%$search%'" :
"SELECT user_name FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row['user_name'] . "</td></tr>";
}
} else {
echo "<tr><td colspan='1'>No results found.</td></tr>";
}
}
$conn->close();
?>
Step 7: Create CSS File
This file provides basic styling for the HTML table and search input. The CSS file styles the search input and table to improve readability and aesthetics.
CSS
/*live-search/style.css */
body {
font-family: Arial, sans-serif;
margin: 20px;
}
input[type="text"] {
width: 300px;
padding: 10px;
font-size: 16px;
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 10px;
}
th,
td {
border: 1px solid #ddd;
padding: 8px;
}
th {
background-color: #f4f4f4;
}
Step 8: Run the Project
- Place these files in the web server root directory (e.g., htdocs for XAMPP).
- Start the XAMPP server, click on start of Apache and MySQL.
- Open a web browser.
- Go to http://localhost/live-search/index.html
Output:
Final output
Similar Reads
Building a REST API with PHP and MySQL This brief tutorial is a step-by-step guide on how to develop a REST API using PHP and MySQL. REST API will implement HTTP commands (Get, Post, Put, DELETE) and response will be in form of JSON. For development setup, we will be using the XAMPP while for testing of the API, we will use the Postman a
5 min read
Creating a Registration and Login System with PHP and MySQL A registration and login system is a fundamental component of many web applications and provides user authentication and security. This allows users to create an account log in with their login credentials and manage their session securely. By using PHP for server-side scripting and MYSQL for databa
12 min read
How to Make a search function using Node Express and MYSQL In this article, we will learn how to create a search function using Node with Express framework to search terms inside MYSQL tables. Prerequisites:MySQLNode JSExpress JSWe will discuss the following methods to search: Table of Content Searching term with partial matchSearching term with exact match
5 min read
How to make a connection with MySQL server using PHP ? MySQL is a widely used database management system that may be used to power a wide range of projects. One of its main selling features is its capacity to manage large amounts of data without breaking a sweat. There are two approaches that can be used to connect MySQL and PHP code, which are mentione
3 min read
Create a Small CRM using PHP and MySQL CRM stands for Customer Relationship Management, which is a strategy for a set of practices, and a technology designed to manage and analyze customer interactions and data throughout the customer lifecycle. Manage contacts by adding, updating, and deleting information such as name, email, phone, and
6 min read
PHP | Inserting into MySQL database Inserting data into a MySQL database using PHP is a crucial operation for many web applications. This process allows developers to dynamically manage and store data, whether it be user inputs, content management, or other data-driven tasks. In this article, We will learn about How to Inserting into
6 min read
Build a Grocery Store Web App using PHP with MySQL In this article, we are going to build a Grocery Store Web Application using PHP with MySQL. In this application, we can add grocery items by their name, quantity, status (pending, bought, not available), and date. We can view, delete and update those items. There will be a date filtering feature wh
7 min read
Highlighting Search Results with Elasticsearch One powerful open-source and highly scalable search and analytics web application that can effectively carry out efficiently retrieving and displaying relevant information from vast datasets is Elasticsearch. Itâs also convenient that Elasticsearch can highlight the text matches, which allows users
4 min read
Online FIR Web App using PHP with MySQL In this article, we are going to build an Online FIR Web Application using PHP with MySQL. In this application, we can file cases from anywhere by their name, complaint, status (pending or solved), and date of incidence, date of registration. Only the admin can view, delete and update status. A comp
10 min read
Getting Started with PHP PHP (Hypertext Preprocessor) is a powerful scripting language widely used for web development. Whether you're looking to create dynamic web pages, handle form data, interact with databases, or build web applications, PHP has you covered. In this guide, we'll take you through the basics of PHP, cover
7 min read