Simple jQuery autocomplete example using php and ajax

jquery autocomplete request using php and ajax

jQuery autocomplete example using php and ajax is one of the most important features of modern websites. To create an autocomplete, using an AJAX call to build a list and to display the list using jquery ui autocomplete.
The easiest and efficient method to create an autocomplete is jquery and jquery-ui. You can download the autocomplete widget from jquery-ui official website.

In this tutorial, I will create an autocomplete example using the counties table. If you don’t have countries list, copy the SQL query from my previous article SQL query to insert all countries into a database.

This autocomplete example has the following properties:

1. Full working demo of this example, see at the end of this article content for download and demo options:
2. PHP and mysqli are used as server side technologies.
3. Ability to search and filter autcomplete data.

When user input in autocomplete search box, an AJAX call/request is made to a php file which is used in the query.autocomplete function with a parameter “q” in the query string. For example, if you type “afg” the following AJAX call be fired.

So, when user types “afg” in autocomplete input, the AJAX call autocomplete.php?q=afg creates and returns the following JSON data.

[
{"name":"Afghanistan"}
]

Below is the HTML and jquery code used in this example.

<html>
<head>
<title>jQuery autocomplete example with ajax call </title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" type="text/css" />
<link href="css/font-awesome.css" rel="stylesheet">
<link href="css/styles.css" rel="stylesheet">
</head>
<body>

<div class="search-container">
	<input type="text" name="suggesionBox" id="suggesionBox" class="search" autocomplete="off" /> 
	<button class="btn-icon-search"><i class="fa fa-search" aria-hidden="true"></i></button>
</div>

<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="js/jquery-ui.min.js"></script>
<script type="text/javascript">
jQuery(function() {
 jQuery("#suggesionBox").autocomplete({
	source: function(req, rsp) {
		var formattedResponsealue = [];
		
		console.log(req.term);
		jQuery.ajax({
			type: "POST",
			url: "countries.php",
			dataType: 'json',
			data: jQuery.extend({q: req.term}, {}),
			success: function(data) {
				jQuery.each(data, function(key, value) {
					formattedResponsealue.push(value.name);
				});
				rsp(formattedResponsealue);
			},
			error:function(e){
				alert("Here");
			}
	 });
	}
 });
});
</script>

</body>
</html>

Below is the PHP code that is used in ‘countries.php’

<?php

	include("dbcon.php");

	$str = $_POST['q'];

	$selSQL = "SELECT name FROM tbl_countries where name like '%".$str."%'";
	$result = $conn->query($selSQL);
	$user = [];

	if($result->num_rows > 0){
		while($row = $result->fetch_assoc()) {
			//printArray($row);
			$user[] = $row;
		}
	}
	
	print json_encode($user); exit;
	
?>

The code used for database case connection, if you need more on database case connection read my article on How to connect to MySQL database using PHP.


<?php
ob_start();
session_start();

$servername = "localhost";
$username = "root";
$password = "";
$database = "test";

// Create connection
$conn = new mysqli($servername, $username, $password,$database);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

?>

Download / Demo

You may also like...