Implementing jQuery AutoComplete with ASP.NET and PHP
Here I’ll show you how to use jQuery AutoComplete with ASP.NET & PHP.
For this demonstration I’m using Jörn Zaefferer jQuery Plugin that you can download from jQuery and also from author’s site here.
There are number of jQuery Autocomplete plugins out there, you may found here.
First of all get the latest jQuery library from here and download the jQuery Autocomplete plugin from here.
Now create a new web site in visual studio 2005/2008 or open an existing one. Open the default.aspx or any page of your choice and add the reference of jQuery library and autocomplete files in head section as shown below.
<head id="Head1" runat="server">
<title>Auto complete Demo</title>
<script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>
<script src="Scripts/jquery.autocomplete.js" type="text/javascript"></script>
<link href="jquery.autocomplete.css" rel="stylesheet" type="text/css" />
</head>
Now add the following code in the body section.
<form id="form1" runat="server">
<div>
<p>
<input id="txtAutocomplete" name="txtAutoComplete" /></p>
</div>
<script type="text/javascript">
$(document).ready(function() {
$("#txtAutocomplete").autocomplete("AutoCompleteHandler.ashx", {
width: 200 //you can set various options here
});
});
</script>
</form>We are done with the frontend, before moving on to the server side code getting autocomplete list, we first understand what we’ve done till now.
Adding reference to the jQuery library and Autocomplete files are straight forward, before going further it must be added in the head section of your ASP.NET webform or your master page.
Next I add an input element of type text to the page and named it “txtAutocomplete” this is our target on which we attach autocomplete feature, moving next I add a script block of type javascript which actually done what we want, I add the code in jQuery’s document.ready function which ensures that all the elements we are referencing are available. In that function we attach autocomplete feature to the text box we define earlier.
The general syntax of Autocomplete is:
autocomplete( url or data, [options] )
Arguments:
- [url] or [data] type may be string in case of url or array in case of data.
An URL pointing at a remote resource or local data as an array.
- options (optional) of type jQuery options
A set of key/value pairs that configure the autocomplete. All options are optional.
You can see the first parameter of the autocomplete plugin is pointing to the “AutoCompleteHandler.ashx” file which is a generic handler in .NET which fulfill our request of getting autocomplete list from the data store.
Note: You can get the data from local source as well, I’ll show you how you can accomplish this in a moment, so read on.
Also when calling the autocomplete function you might declare some useful option that may change the behavior as desires.
You can find the complete list of options here.
Now move to the server-side code in ASP.NET C#, which will fetch the list as an array from the datastore, here I create a generic handler which simply process our request and give the response quickly, here is the code listing:
<%@ WebHandler Language="C#" Class="AutoCompleteHandler" %>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.IO;
using System.Text.RegularExpressions;
public class AutoCompleteHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string strData = string.Empty;
if (context.Request.QueryString["q"] != null)
{
string q = context.Request.QueryString["q"];
string limit = context.Request.QueryString["limit"];
try
{
string[] custs;
using (var db = new AdventureWorksDataContext())
{
custs = db.Customers.Where(c => c.LastName.StartsWith(q.Trim())).OrderBy(c => c.LastName).Select(c => c.LastName).Take(int.Parse(limit)).ToArray();
}
strData = string.Join(Environment.NewLine, custs.Take(int.Parse(limit)).ToArray());
}
catch { }
finally
{
}
}
context.Response.ContentType = "text/plain";
context.Response.Write(strData);
}
public bool IsReusable
{
get
{
return false;
}
}
}Here the code is very easy to understand, first we’ll lookup the request variables that are send by the autocomplete plugin which are named “q” and “limit”, q has the lookup string and limit as the name suggest is used to restrict the number of rows taken from the datastore, I then query the datastore with the help of LINQ to SQL and return data as the string array, since autocomplete plugin expects data as a plain text, and each list item is presented on the new line, then I simply return that string containing data to the responses stream and from now Autocomplete will take care of all processing to represent data.
One question will arise in your mind that if we are getting data from database then on each & every request it will hit the database, fortunately, autocomplete plugin has a caching feature which will cache the data locally for each matched look-up string. It really implemented good caching feature. I tested it through MS SQL Server Profiler.
Autocomplete plugin has a style attached with it, you can modify it for your test. I modify it as follows, which shows animated graphic while fetching data from the server, here is the css style:
.ac_input
{
width: 200px;
background-image: url('images/throbber.gif');
background-position: 100% 2px;
background-repeat: no-repeat;
}
.ac_loading
{
background-position: 100% -18px;
}Now, you can test your autocomplete plugin in ASP.NET.
I said you earlier that instead of remote data, we can simply use local array object to fulfill our requirement, all you need to do is just using array object instead of remote data [Remote URL] as follows:
<script type="text/javascript">
$(document).ready(function() {
var data = "Shahnawaz Khan ASP.NET C# PHP SQL MYSQL Microsoft CSS Events Ajax Flash nawaznet Twitter Facebook".split(" ");
$("#txtAutocomplete").autocomplete(data, {
width: 200, scroll: false //you can set various options here
});
});
</script>ASP.NET implementation is complete and now we move on to the PHP implementation, so that it completes this post, As I’m new to PHP so I’ll return only simple array data, in the near future I’ll update this PHP code to get data from MySQL.
Implementing PHP is straight forward, all you need to create a php file with the following code and call that php file in the autocomplete’s url argument.
<?php
$q = strtolower($_GET["q"]);
if (!$q) return;
$items = array(
"Shahnawaz Khan",
"Smart Guy",
"ASP.NET",
"Always do right",
"Black Mamba",
"Pink",
"Drupal",
"SDK",
"My SQL",
"Microsoft"
);
foreach ($items as $key=>$value) {
if (strpos(strtolower($value), $q) !== false) {
echo "$value\n";
}
}
?>Suppose you name it phpac.php then you can call it as follows:
<script type="text/javascript">
$(document).ready(function() {
$("#txtAutocomplete").autocomplete("phpac.php", {
width: 200, scroll: false //you can set various options here
});
});
</script>Note: Make sure that you call above php script from normal html page, there is no need to call it from ASP.NET page.
I’m done, I think it’s very useful to show autocomplete when you are implementing search feature in your website.
Hope this works!
| Attachment | Size |
|---|---|
| jquery.autocomplete.asp_.net_.zip | 47.88 KB |

Comments
Lornetki
Cool blog, i want to start blogging too, what script is the best for my first blog ?
Really Awesome article
man u did a great job, i was browse the internet all the day trying to find autocomplete ,jquery asd asp.net but i get nothing till i find yours.
Thanks a lot
Luki sportowe
This topic is very interesting, keep us posting..
Fajerwerki
interesting blog, bookmarked for the future referrence, what template do you use ?
Re: Fajerwerki
Thank you!
Did you mean site template? If so I'm using my own theme and you can get it here.
Regards!
Shahnawaz
BEST BEST BEST
I've tried many samples of AutoComplete stuff... ASP.NET Ajax extender is a completely jerk relatively jQuery solution...
Shahnawaz, thank you so much, this is the best&simple... And it works ;)
Re: BEST BEST BEST
Thank you!
such responses definitely boost me to deliver more solution(s) to make web better.
Regards!
Shahnawaz
Thank You for good article
Thank you for your good tutorial about auto-complete forms. I use this in my project. my project language is Farsi (Persian) and I changed some css items to make a good Right-to-Left view.
tatoo designs
Your blog is awsome, bookmarked, regards tatoorexion
tattoo designs
Re: tatoo designs
Thanks!
Keep visiting.
Regards!
Shahnawaz
Auto Complete
Hi I'm relatively new to .NET. I'm using 2.0. Is this example 3.5? Can I also ask how you would implement this if you wanted to carry this out on say a Customer Table (first name/surname) along with carring out auto complete on address informaton of say an Organisation or a Customer. Would you require a different webservice for each?
Hope you can help
Re: Auto Complete
Yes, this auto complete demo is for ASP.NET 3.5+ as it uses LINQ to SQL for fetching data from datastore. you can do what you want, just provide query in LINQ to SQL according to your needs, for this you have to learn LINQ first which is essential part of the .Net Framework.
Hope this works!
Regards!
Shahnawaz
Best article I've seen on this topic
Thanks for this article. This is the best demo I've yet found on integrating ASP.NET and jquery autocomplete. Good work!
Re: Best article I've seen on this topic
Thanks!
It'll really appreciate me to post more with good quality stuff.
Regards!
Shahnawaz
Post new comment