AJAX Autocomplete: Using AJAX to Implement the Autocomplete Functionality

ajax autocompleteAJAX is an acronym that stands for Asynchronous JavaScript and XML. AJAX lets you create efficient, interactive web applications when it’s used with XML, CSS, HTML and JavaScript. It uses XHTML to store and display content, CSS for the design of the presentation and JavaScript to make the content dynamic (interactive, real time). If you’re looking to learn AJAX (and web development in general) you need to be familiar with XHTML, CSS and JavaScript. This course gives you a good intro to Ajax and how it ties in with the other technologies.

The term AJAX was coined in 2005, after Google used AJAX to make Gmail and Google Maps. AJAX helped make these applications asynchronous. What does that mean exactly? If you hit a button on an application and the page has to reload in response to your request, it employs synchronous technology. If it doesn’t have to reload and instead processes your request in the background and then displays it, it is asynchronous (done through JavaScript). With AJAX, even simple Mouse movement is enough to trigger an event (reaction from the web server). This makes surfing a website an intuitive and enjoyable experience for a user.

In this tutorial, we’re going to take a look at how you can use AJAX to provide the autocomplete functionality in a text box. You need to know the basics of web development to understand this tutorial. You can learn more about web development with Ajax by taking this course.

What is the autocomplete functionality exactly? Open Google search and type a few words in the text box. It will attempt to complete the sentence you’re trying to type. This is essentially what the autocomplete functionality is (though they call it search prediction).

Using AJAX to Autocomplete

You can use AJAX to provide the user a list of options in a drop down menu below the text box, based on what the user is typing in it. Of course, as you can imagine, this can be very complicated to accomplish, as there can be hundreds of thousands of alternatives and variations for each word the user types. Most websites uses premade AJAX autocomplete toolkits or widgets to provide the autocomplete functionality. These toolkits and widgets usually link to an external web service that provides the database from which the possible autocomplete options are chosen.

We’ll take a look at some of the more popular toolkits and widgets out there and attempt to explain parts of their source code. You can make your own widget for this, of course, but it’s very complex and can be a bit of a task. If you like challenges, we can help you get started, with this course on Ajax development.

The Autocomplete Widget

You can use the Autocomplete widget with any field that can receive text input, like <input> elements and <textarea> elements, as well as elements that have the contenteditable attribute. The plugin produces a list of entries that match when you focus on the blank field (mouse event) or enter something into it. The more the characters typed into the field, the better the filter on the plugin works.

The Autocomplete widget will also store previously made entries and display them. It also supports additional features like associating a text entry with some other information. For example, if you enter the name of the city, it can display the zip code of that city.

The source option in the plugin lets you choose the data source from which results are selected and displayed. It’s possible to link the plugin to a remote database, which has dozens of entries, or to a remote database with millions of possible results. Large websites usually link to remote databases, which lets them provide a better service to their users.

Let’s take a look at the basic autocomplete functionality that uses a local database to display results (from the source code of the plugin):

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function() {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scheme"
];
$( "#tags" ).autocomplete({
source: availableTags
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
</body>
</html>
Output:
Various “tags” – the names of programming languages- will be displayed to the user, depending on what he types.

In the program, they’ve included several tags which are the names of programming languages like Ruby, Python and PHP. When the user begins to type something in the text box, some of these tags will get displayed in the dropdown menu, depending on what he types. For example, if he enters “p” in the box, the drop down menu will have “Perl”, “Python” and “PHP” as autocomplete options.

This is one of the most basic functionalities of the widget. You can download the plugin from the official website here. We recommend that you download it and experiment with the source code to understand it better. If you need help with the terminology or any parts of the source code, refer to our tutorials or just take our web development course.

AutoComplete ASP.NET AJAX Extender

The AutoComplete extender (that works with the ASP.NET) framework attaches to your text box to provide the autocomplete functionality. A web service is used to provide the suggestions in the drop down box. If you type more than a word (or a certain minimum word length) in the text box, the web service will display phrases as the result in the dropdown menu.

You can attach the AutoComplete extender with the following code:

<ajaxToolkit:AutoCompleteExtender
    runat="server"
    ID="autoComplete1"
    TargetControlID="myTextBox"
    ServiceMethod="GetCompletionList"
    ServicePath="AutoComplete.asmx"
    MinimumPrefixLength="2"
    CompletionInterval="1000"
    EnableCaching="true"
    CompletionSetCount="20"
    CompletionListCssClass="autocomplete_completionListElement"
    CompletionListItemCssClass="autocomplete_listItem"
    CompletionListHighlightedItemCssClass="autocomplete_highlightedListItem"
    DelimiterCharacters=";, :"
    ShowOnlyCurrentWordInCompletionListItem="true">
        <Animations>
            <OnShow> ... </OnShow>
            <OnHide> ... </OnHide>
        </Animations>
</ajaxToolkit:AutoCompleteExtender>

The italicized code is optional. The TargetControlID field will hold the name of your text box. The service method is the web service method that must be called each time to display the result, while the service path is the address of the web service. The rest of the code is optional.

You can enable or disable caching by specifying a true or false Boolean value. If caching is enabled, the web service is called only once for an identical prefix, which speeds up the autocomplete process. You can set the minimum prefix length to a number of your choice. For example, if it is set to “2”, you will have to type 2 characters in the search box before the web service will be called. You can also specify the number of results that the web service should retrieve. The CompletionSetCount is 20 by default in the above source code. You can set up a lower value to speed up the process, but this will limit the number of options displayed drastically and will reduce the usefulness of the autocomplete feature. The delimiter character will be used to set the character that separates words for the web service (like “,”, for example).

The AJAX AutoComplete extender is available as part of the ASP.NET AJAX Control toolkit. You can check out the official website for more information. Also check out the Autosuggest/ Autocomplete with Ajax widget here, and the Ajax AutoComplete for jQuery widget here.

If you want to get some hands on experience with AJAX and web development, as well as more detailed guidance on how to create your own AJAX toolkits or widgets, you can sign up for this course.