Ajax live data search using jQuery, PHP and MySQL
In this post, you will learn how to develop live search using Ajax, jQuery, PHP, and MySQL.
On most of the sites, we can see there is one search bar where we can type in search content and get a search result with page refreshing. A live search is a search feature that shows the result instantly while you start typing some characters in the search input box. You can see the search results on sites like the Google Search Autocomplete, Facebook, and Twitter. They have amazing live search functionality. It makes it simpler for the clients to discover what they are looking for. It delivers the result without page refresh. This functionality can be done using Ajax with jQuery.
With the assistance of jQuery we can utilize Ajax http dom work, with the assistance of this capacity, it searches for information on the server side and sends back outcome to the front end website page without a page refresh. These are the step-by-step process to live search data using Ajax.
Creating Database
Suppose we have the following 'employee' table. Execute the following query to create the employee table in your MySQL database.
CREATE TABLE IF NOT EXISTS `employee` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`emp_name` varchar(150) NOT NULL,
`email` varchar(150) NOT NULL,
`phone` varchar(100) NOT NULL,
`created_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=11 DEFAULT CHARSET=latin1;
INSERT INTO `employee` (`id`, `emp_name`, `email`, `phone`, `created_date`) VALUES
(1, 'John', This email address is being protected from spambots. You need JavaScript enabled to view it. ', '2323234543', '2019-06-05 15:36:07'),
(3, 'Priska', This email address is being protected from spambots. You need JavaScript enabled to view it. ', '9393452387', '2019-05-28 15:36:07'),
(7, 'Alaya', This email address is being protected from spambots. You need JavaScript enabled to view it. ', '3290349906', '2019-03-02 11:16:07'),
(8, 'Carle', This email address is being protected from spambots. You need JavaScript enabled to view it. ', '9059098968', '2019-06-01 10:06:07'),
(9, 'Amma', This email address is being protected from spambots. You need JavaScript enabled to view it. ', '6750390948', '2019-04-05 16:30:07');
Configuration File
Let's create the configuration file 'config.php'. Please make sure to replace the hostname, username, password and database with your database credentials.
<?php
//Database details
$db_host = 'localhost';
$db_username = 'username';
$db_password = 'password';
$db_name = 'database_name';
//Create connection and select DB
$conn = mysqli_connect($db_host, $db_username, $db_password, $db_name);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
index.php
Here is the main file that we will call in the browser. First, we have imported the 'config.php' file at the top and then, written HTML code for the search input box and to show a search result. When the user starts typing on the search bar, the load_data() function will be called. This function calls the Ajax file 'searchresult.php' and fetches the employee information based on the search content and stores the fetched data in the div with the id 'result'.
<?php
include("config.php");
?>
<html>
<head>
<title>Ajax live data search using jQuery PHP MySQL</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
<script>
$(document).ready(function(){
load_data();
function load_data(query)
{
$.ajax({
url:"searchresult.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('#result').html(data);
}
});
}
$('#search').keyup(function(){
var search = $(this).val();
if(search != '')
{
load_data(search);
}
else
{
load_data();
}
});
});
</script>
</head>
<body>
<div class="container-fluid">
<div class="content-wrapper">
<div class="container">
<h1>Ajax live data search using jQuery PHP MySQL</h1>
<div class="row">
<div class="col-xs-12">
<input type="text" name="search" id="search" placeholder="Search" class="form-control" />
<div id="result"></div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
searchresult.php
In the given file, we have received the 'query' using the global variable $_POST. Next, we have fetched the employee information from the 'employee' table and represented it in a tabular format.
<?php
require ('config.php');
$return = '';
if(isset($_POST["query"]))
{
$search = mysqli_real_escape_string($conn, $_POST["query"]);
$query = "SELECT * FROM employee
WHERE id LIKE '%".$search."%'
OR emp_name LIKE '%".$search."%'
OR email LIKE '%".$search."%'
OR phone LIKE '%".$search."%'
";}
else
{
$query = "SELECT * FROM employee";
}
$result = mysqli_query($conn, $query);
if(mysqli_num_rows($result) > 0)
{
$return .='
<div class="table-responsive">
<table class="table table bordered">
<tr>
<th>ID</th>
<th>Emp Name</th>
<th>Email</th>
<th>Phone</th>
<th>Created Date</th>
</tr>';
while($row1 = mysqli_fetch_array($result))
{
$return .= '
<tr>
<td>'.$row1["id"].'</td>
<td>'.$row1["emp_name"].'</td>
<td>'.$row1["email"].'</td>
<td>'.$row1["phone"].'</td>
<td>'.$row1["created_date"].'</td>
</tr>';
}
echo $return;
}
else
{
echo 'No results containing all your search terms were found.';
}
?>
Output of the above code-
Related Articles
PHP Server Side Form ValidationPHP File Upload MIME Type Validation
Complete HTML Form Validation in PHP
File Upload Validation in PHP
PHP SplFileObject Standard Library
Simple File Upload Script in PHP
Sending form data to an email using PHP
PHP secure random password generator
How to create search filter in PHP
PHP import Excel data to MySQL using PHPExcel
How to display PDF file in PHP from database
How to read CSV file in PHP and store in MySQL
Create And Download Word Document in PHP
PHP SplFileObject Standard Library
Simple File Upload Script in PHP
Sending form data to an email using PHP
Recover forgot password using PHP and MySQL
Php file based authentication
Simple PHP File Cache
How to get current directory, filename and code line number in PHP