etutorialspoint
  • Home
  • PHP
  • MySQL
  • MongoDB
  • HTML
  • Javascript
  • Node.js
  • Express.js
  • Python
  • Jquery
  • R
  • Kotlin
  • DS
  • Blogs
  • Theory of Computation

Ajax live data search using jQuery PHP MySQL

In this article, 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 on the site 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 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 -

PHP Ajax Live Search



Related Articles

PHP Server Side Form Validation
PHP 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




Most Popular Development Resources
Retrieve Data From Database Without Page refresh Using AJAX, PHP and Javascript
-----------------
PHP Create Word Document from HTML
-----------------
How to get data from XML file in PHP
-----------------
Hypertext Transfer Protocol Overview
-----------------
PHP code to send email using SMTP
-----------------
Characteristics of a Good Computer Program
-----------------
How to encrypt password in PHP
-----------------
Create Dynamic Pie Chart using Google API, PHP and MySQL
-----------------
PHP MySQL PDO Database Connection and CRUD Operations
-----------------
Splitting MySQL Results Into Two Columns Using PHP
-----------------
Dynamically Add/Delete HTML Table Rows Using Javascript
-----------------
How to get current directory, filename and code line number in PHP
-----------------
How to add multiple custom markers on google map
-----------------
Get current visitor\'s location using HTML5 Geolocation API and PHP
-----------------
Fibonacci Series Program in PHP
-----------------
How to Sort Table Data in PHP and MySQL
-----------------
Simple star rating system using PHP, jQuery and Ajax
-----------------
Submit a form data using PHP, AJAX and Javascript
-----------------
jQuery loop over JSON result after AJAX Success
-----------------
How to generate QR Code in PHP
-----------------
Simple pagination in PHP
-----------------
PHP MYSQL Advanced Search Feature
-----------------
Recover forgot password using PHP7 and MySQLi
-----------------
PHP Server Side Form Validation
-----------------
PHP user registration and login/ logout with secure password encryption
-----------------
jQuery File upload progress bar with file size validation
-----------------
Simple File Upload Script in PHP
-----------------
Simple PHP File Cache
-----------------
Php file based authentication
-----------------
To check whether a year is a leap year or not in php
-----------------
Calculate distance between two locations using PHP
-----------------
PHP User Authentication by IP Address
-----------------
PHP Secure User Registration with Login/logout
-----------------
How to print specific part of a web page in javascript
-----------------
Simple way to send SMTP mail using Node.js
-----------------
Simple Show Hide Menu Navigation
-----------------
Detect Mobile Devices in PHP
-----------------
Polling system using PHP, Ajax and MySql
-----------------
PHP Sending HTML form data to an Email
-----------------
Get Visitor\'s location and TimeZone
-----------------
Google Street View API Example
-----------------
SQL Injection Prevention Techniques
-----------------
Preventing Cross Site Request Forgeries(CSRF) in PHP
-----------------
Driving route directions from source to destination using HTML5 and Javascript
-----------------
Convert MySQL to JSON using PHP
-----------------
PHP Programming Error Types
-----------------
CSS Simple Menu Navigation Bar
-----------------
Date Timestamp Formats in PHP
-----------------
Set and Get Cookies in PHP
-----------------
How to select/deselect all checkboxes using Javascript
-----------------
How to add google map on your website and display address on click marker
-----------------
How to display PDF file in web page from Database in PHP
-----------------
Write a python program to print all even numbers between 1 to 100
-----------------
PHP Getting Document of Remote Address
-----------------
File Upload Validation in PHP
-----------------


Most Popular Blogs
Most in demand programming languages
Best mvc PHP frameworks in 2019
MariaDB vs MySQL
Most in demand NoSQL databases for 2019
Best AI Startups In India
Kotlin : Android App Development Choice
Kotlin vs Java which one is better
Top Android App Development Languages in 2019
Web Robots
Data Science Recruitment of Freshers - 2019


Interview Questions Answers
Basic PHP Interview
Advanced PHP Interview
MySQL Interview
Javascript Interview
HTML Interview
CSS Interview
Programming C Interview
Programming C++ Interview
Java Interview
Computer Networking Interview
NodeJS Interview
ExpressJS Interview
R Interview


Popular Tutorials
PHP Tutorial (Basic & Advance)
MySQL Tutorial & Exercise
MongoDB Tutorial
Python Tutorial & Exercise
Kotlin Tutorial & Exercise
R Programming Tutorial
HTML Tutorial
jQuery Tutorial
NodeJS Tutorial
ExpressJS Tutorial
Theory of Computation Tutorial
Data Structure Tutorial
Javascript Tutorial






Learn Popular Language

listen
listen
listen
listen
listen

Blogs

  • Jan 3

    Stateful vs Stateless

    A Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities...

  • Dec 29

    Best programming language to learn in 2021

    In this article, we have mentioned the analyzed results of the best programming language for 2021...

  • Dec 20

    How is Python best for mobile app development?

    Python has a set of useful Libraries and Packages that minimize the use of code...

  • July 18

    Learn all about Emoji

    In this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more...

  • Jan 10

    Data Science Recruitment of Freshers

    In this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician...

Follow us

  • etutorialspoint facebook
  • etutorialspoint twitter
  • etutorialspoint linkedin
etutorialspoint youtube
About Us      Contact Us


  • eTutorialsPoint©Copyright 2016-2023. All Rights Reserved.