Top

Follow me and receive all the latest free scripts:

By Email:

Categories
Most Popular Posts

Ajax and jQuery autocomplete tutorial

Ajax and jQuery autocomplete tutorial

Published November 09, 2014 by , category jQuery

AjaxjQueryAutocompleteField

The simplest Ajax and jQuery autocomplete tutorial ever… without jQuery UI

Introduction

As I said, here is the simplest Ajax and jQuery autocomplete suggestions script ever. Keyup on the text field triggers the function, you can setup the minimum characters, Ajax calls the PHP file (sending the current value of the text field) which makes the treatment and sends back a list of matching words.

Live demo

For the demo I use a country list table. So search for a country and select the one you want on the returning list.

Files architecture

index.php
db.class.php

ajax

tuto-autocomplete.php

jquery

jquery-1.10.1.min.js

design

Database structure sample

A simple table with two fields: id, a standard auto increment field and name, insert words inside, for the demo above it's a country list.

CREATE TABLE IF NOT EXISTS `tc_countries` (
  `id` int(3) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) CHARACTER SET latin1 NOT NULL DEFAULT '',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 ;

Database connection

Page db.class.php. More information about the database connection I use here.

HTML / JS code

index.php page, JavaScript code at the bottom, you can place the JS on an external file of course.

Lines are commented.

<!DOCTYPE>
<html>
<head>
	<title>Ajax jQuery Autocomplete</title>
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
</head>

<body>	

<form>
	<input type="text" id="myTextField" />
	<div id="match"></div>
</form>

<script type="text/javascript" src="jquery/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(function() {
	$("#myTextField").on('keyup', function() { // everytime keyup event
		var input = $(this).val(); // We take the input value
		if ( input.length >= 2 ) { // Minimum characters = 2 (you can change)
			$('#match').html('<img src="design/loader-small.gif" />'); // Loader icon apprears in the <div id="match"></div>
			var dataFields = {'input': input}; // We pass input argument in Ajax
			$.ajax({
				type: "POST",
				url: "ajax/tuto-autocomplete.php", // call the php file ajax/tuto-autocomplete.php
				data: dataFields, // Send dataFields var
				timeout: 3000,
				success: function(dataBack){ // If success
					$('#match').html(dataBack); // Return data (UL list) and insert it in the <div id="match"></div>
					$('#matchList li').on('click', function() { // When click on an element in the list
						$('#myTextField').val($(this).text()); // Update the field with the new element
						$('#match').text(''); // Clear the <div id="match"></div>
					});
				},
				error: function() { // if error
					$('#match').text('Problem!');
				}
			});
		} else {
			$('#match').text(''); // If less than 2 characters, clear the <div id="match"></div>
		}
	});
});
</script>

</body>
</html>

PHP code

Page tuto-autocomplete.php, lines are commented.

<?php
include('../db.class.php');
$bdd = new db();

if($_POST) {
	$input = $_POST['input'];
	
	$matchString = $bdd->getAll('SELECT * FROM tc_countries WHERE name LIKE "%'.$input.'%"'); // Search matching elements in database
	if (!empty($matchString)) { // If not empty list
		echo '<ul id="matchList">'; // Create UL list
			foreach($matchString as $matchString) { // Loops
				$matchStringBold = preg_replace('/('.$input.')/i', '<strong>$1</strong>', $matchString['name']); // Replace text field input by bold one
				echo '<li id="'.$matchString['name'].'">'.$matchStringBold.'</li>'; // Create the matching list - we put maching name in the ID too
			}
		echo '</ul>';
	}
}
?>

Conclusion

I don't know how it can be simpler! Anyway, if you have any questions, ask below .

Happy coding!

About Simon Laroche
Simon Laroche on Google+
Simon Laroche on Twitter
Simon Laroche on Facebook
Simon Laroche on Pinterest
Simon Laroche on LinkedIn
: I am a Coder, Designer, Webmaster and Expert SEO Consulting, I'm also a wise traveller and an avid amateur photographer. I created the website TipoCode and many others such as Landolia: a World of Photos...

If you need help about this script, please leave a comment below. I reply as much as I can depending of my time, you may also get help from others.
I also offer a paid support, if you are in the need to adapt or create a script...

Leave a comment

Comments (4 comments)

Simon Laroche
Simon Laroche Posted on July 01, 2016
@Richard : well it's possible of course to create an autocomplete with a pagination. However it's not something that we can do in 5 minutes, not even 1 hour... Maybe some day I will make a tutorial with this kind of system...
Richard Posted on June 30, 2016
Hello Simon,
How can we add a pagination?? ie : limit the number of results to 5 and have an arrow to navigate through the page numbers...?

Thanks
Simon Laroche
Simon Laroche Posted on December 16, 2014
We can add key event to use arrows up and down to navigate the autocomplete list. Here is the complete jQuery code. You will see the code I have added:


$(function() {
$("#myTextField").bind('input', function() {
var index = -1; // set up var index
var input = $(this).val();
if ( input.length >= 2 ) {
$('#match').html('<img src="design/loader-small.gif" />');
var dataFields = {'input': input};
$.ajax({
type: "POST",
url: "ajax/tuto-autocomplete.php",
data: dataFields,
timeout: 3000,
success: function(dataBack){
$('#match').html(dataBack);
$('#matchList li').on('click', function() {
$('#myTextField').val($(this).text());
$('#match').text('');
});

$('#myTextField').on('keyup', function(e) {
var key = e.which;

var m = false;
if ( key == 38 ) {
index--;
if(index < 0){
index = 0;
}
m = true;
$(this).val($('#matchList li').eq(index).text());
} else if ( key == 40 ) {
index++;
if(index > $('#matchList li').length - 1){
index = $('#matchList li').length - 1;
}
m = true;
$(this).val($('#matchList li').eq(index).text());
}

if(m){
$('#matchList li.active').removeClass('active');
$('#matchList li').eq(index).addClass('active');
}

if ( key == 27 ) {
// Esc key
$('#matchList').hide();
}
});
},
error: function() {
$('#match').text('Problem!');
}
});
} else {
$('#match').text('');
}
});

$('html').click(function() {
$('#match').text('');
});
});
Simon Laroche
Simon Laroche Posted on December 16, 2014
Tip: if you want to hide the <div id="match"> (autocomplete results) block when mouse click outside, add this:


$('html').click(function() {
$('#match').text('');
});