Are you looking to integrate jQuery Autocomplete on your website? jQuery Autocomplete is like Google Search where a user enters some letters and the result set matching with typed letters is pre-populated.
Integrating Autocomplete is simple and straightforward. You need to include JS and CSS files provided on jQuery UI, and have an Ajax script to return a matching result set.
In this tutorial, I will take an example of users. When you start typing letters, the user’s list will appear matching their name to typed letters.
Database Connection
For our tutorial, we require a few entries to show up so create a database table using the below SQL query.
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
Add some dummy data to the table. I am entering 4 rows. You can enter as many as you want.
INSERT INTO `users` (`id`, `name`) VALUES
(1, 'Sam'),
(2, 'Sandy'),
(3, 'Adam'),
(4, 'Andrew');
Next, write a code for the database connection. I am creating a class file for it. I would also define the method which returns matching rows as per keyword. This method will be used when we integrate Autocomplete in the next steps.
class-db.php
<?php
class DB {
private $dbHost = "DB_HOST";
private $dbUsername = "DB_USERNAME";
private $dbPassword = "DB_PASSWORD";
private $dbName = "DB_NAME";
public function __construct(){
if(!isset($this->db)){
// Connect to the database
$conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName);
if($conn->connect_error){
die("Failed to connect with MySQL: " . $conn->connect_error);
}else{
$this->db = $conn;
}
}
}
public function search_users($q = '') {
$result = [];
$sql = $this->db->query("SELECT name FROM users WHERE name LIKE '".$q."%'");
while ($row = $sql->fetch_assoc()) {
$result[] = $row['name'];
}
return json_encode($result);
}
}
How to use jQuery Autocomplete with Ajax
To see jQuery Autocomplete in action, let’s take one text field. When a user starts typing letters in this field, pre-populated data should appear from which the user can select a specific one.
Create the index.html
file and add the code below to it.
<link rel="stylesheet" href="//code.jquery.com/ui/1.13.0/themes/base/jquery-ui.css" />
<input type="text" id="names" placeholder="Your Name" name="names" />
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.13.0/jquery-ui.js"></script>
In the above HTML, I have included the required CSS and JS files. I also gave id “names” to the text field. On this id, I would call the autocomplete method.
Next, let’s write JavaScript code that uses autocomplete, give a call to the Ajax file, grab the response, and append it to the input field.
<script type="text/javascript">
jQuery(function($) {
$("#names").autocomplete({
source: function(term, response){
$.getJSON('search.php', { q: term }, function(data){ response(data); });
}
});
});
</script>
In the search.php
file, we get the entered letters and fetch records from the database. This response then returns to the JavaScript code written above.
<?php
require_once 'class-db.php';
$q = $_REQUEST['q']['term'];
$db = new DB();
$result = $db->search_users($q);
echo $result;
die;
That’s it! Give it a try and you should see your Autocomplete feature works as expected.
I hope you understand how to use jQuery Autocomplete with Ajax in PHP. Please share your thoughts and suggestions in the comment section below.
Related Articles
- Ajax File Upload with PHP and jQuery
- Validate Google reCAPTCHA using JavaScript
- How to Detect Browser in PHP and JavaScript
If you liked this article, then please subscribe to our YouTube Channel for video tutorials.