In this post I want to show how to create autocomplete search using jQuery and ASP.NET web service, by using simple code and style I will explain how the work of autocomplete search with custom result without use jQuery UI Autocomplete widget becouse i want the result with images and links like facebook search.
Database:
I will use sql server database to create sample table with sample data which we search about.
CREATE TABLE site_tb ( title varchar(50), img varchar(50), href varchar(150) )
As you see, we created site table with three columns: title (site title), img (to save image file name) and href (to save the link of site title).
Now we will insert sample data that is representing to social networks websites:
INSERT INTO site_tb (title,img,href)
VALUES ('Facebook is a social network' ,'fb.png' ,'http://www.facebook.com')
INSERT INTO site_tb (title,img,href)
VALUES ('Twitter is a social network' ,'tw.png' ,'http://www.twitter.com')
INSERT INTO site_tb (title,img,href)
VALUES ('Google+ is a social network' ,'gp.png' ,'http://plus.google.com')
INSERT INTO site_tb (title,img,href)
VALUES ('YouTube is a place to discover, watch' ,'yt.png' ,'http://www.youtube.com')
Web Page
Now we will create new website project using visual studio, in Default.aspx page we will add this style:
<!--
.content
{
margin:50px auto;
text-align:center;
width:422px;
}
#txtSearch
{
padding:10px;
border:solid 1px #cccccc;
width:400px;
color:#555555;
font: 18pt tahoma;
}
.divResult
{
position:absolute;
background-color:#F2F2FF;
border-style:solid;
border-width:1px;
border-color:#999999;
padding:10px;
margin:0 auto;
width:400px;
text-align:left;
display:none;
}
.img
{
width:60px;
height:60px;
margin:5px;
float:left;
}
.txtResult
{
display:block;
width:300px;
height:60px;
padding:5px;
margin:5px;
color:#555555;
font: 14pt tahoma;
text-decoration:none;
}
.loading
{
font: 10pt tahoma;
text-align:center;
}
.record
{
margin:2px;
}
-->
In body of page add the following:
<div class="content">
<input id="txtSearch" onkeyup="search()" type="text" />
<div class="divResult">
<div class="loading">Loading..</div>
<div class="record"></div>
</div>
</div>
And we will add jquery library (download it from jquery.com)
<script src="jquery-1.4.3.min.js" type="text/javascript"></script>
we will use client event on text input which it is onkeyup that fire when user press down then up on the key, this event will call javascript function.
<script type="text/javascript">
function search() {
if ($("#txtSearch").val() != "") {
$(".divResult").show(); //show div block that contain on result
$(".loading").show(); // show loading text while getting result
//here we will put code that call search function on web service
}
else {
$(".divResult").hide(); //hide div that contain result when the input text is empty
$(".record").html(""); //also loading text when the input text is empty
}
}
</script>
You can test this simple code.
Web Service
Now we will create web service that contain Search function, Search function will return list of objects.
1- In visual studio add new Web Service and name it WebService.asmx
2- Declare class searchResult above of the WebService class in the same file
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using System.Data.SqlClient;
public class searchResult
{
public string Title;
public string img;
public string href;
}
//Etc.
3- In the same WebService file,allow Web Service to be called from script by uncomment the following code
[System.Web.Script.Services.ScriptService]
4- Using the GenerateScriptType attribute to define types (searchResult in our example) that should be available to the client
[System.Web.Script.Services.GenerateScriptType(typeof(searchResult))]
5- In the WebService class declare Search function that take string parameter and return array of searchResult objects
[WebMethod]
public searchResult[] Search(string txtSearch)
{
//txtSearch parameter will receive a text from client to search about
}
6- write a code to connect to database and search about sites by part of txtSearch string parameter
[WebMethod]
public searchResult[] Search(string txtSearch)
{
//Semuler to slow internet connection
//System.Threading.Thread.Sleep(2000);
//Declare collection of searchResult
List resultList = new List();
string constr = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["conn"].ConnectionString; ;
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "select * from site_tb where title like '%" + txtSearch + "%'";
try
{
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
searchResult result = new searchResult();
result.Title = dr["title"].ToString();
result.img = dr["img"].ToString();
result.href = dr["href"].ToString();
resultList.Add(result);
}
con.Close();
return resultList.ToArray();
}
catch
{
return null;
}
}
Call Web Service Using jQuery:
Now we return to javascript to call web service using jquery and to display search result by ajax call
<script type="text/javascript">
function search() {
if ($("#txtSearch").val() != "") {
$(".divResult").show(); //show div block that contains on result
$(".loading").show(); // show loading text while getting result
//call web searvice
$.ajax({ type: "POST",
url: "WebService.asmx/Search", //function that in web service
data: "{txtSearch:'" + $("#txtSearch").val() + "'}",// passing value of txtSearch input
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
//declaer client object and set to it returned result from web sevice function
var result = response.d;
$(".record").html(""); // clear previous result
//looping in 'result' array to get data and fill it inside ".record" div as html
$.each(result, function(index, res) {
//append img tag inside ".record" div
$('<img />', {
src: 'images/' + res.img,
alt: res.Title
}).addClass("img").appendTo('.record');
//append anchor tag inside ".record" div
$('<a></a>', {
href: res.href,
text: res.Title
}).addClass("txtResult").appendTo('.record');
$(".record").append("<hr />");
});
//hide loading div when the data was got
$(".loading").hide();
},
error: function(msg) {
$(".record").html(msg.d);
}
});
}
else {
$(".divResult").hide(); //hide div that contains result when the input text is empty
$(".record").html(""); //also loading text when the input text is empty
}
}
</script>
Conclusion:
ASP.NET provides excellent support for calling Web Services with writing a lot of custom JavaScript code to handle the request and response messages using jquery and ajax. In this article you’ve seen how to use .NET Web Service and call it via jquery to get list of data as ajax call.








August 13, 2011 at 5:34 pm
Good job, your post is amazing, like out of this world.
August 14, 2011 at 12:05 am
dont use with sql now , I use ruby
August 14, 2011 at 2:18 am
Excellent read, I just passed this onto a colleague who was doing a little research on that.
August 21, 2011 at 9:33 pm
I really liked the article, and the very cool blog
December 17, 2011 at 11:06 am
Hi Ibrahim,
This is really useful script. Can I get a download?
Thanks
December 17, 2011 at 12:47 pm
Thanks Quang for your comment,
You can copy the code above
January 28, 2012 at 8:59 pm
can anyone confirm that it selects the text as tags ?
June 18, 2012 at 12:03 am
Amazing code, but id doesnt work on IE 8. I tjink reason is command “each” used.
Any suggestion?
August 23, 2012 at 8:02 pm
how i can fill the input with one of the results, i tried clicking and nothing happens, the input field just still blank