Google Search

Tuesday, April 1, 2008

Ajax AutoCompleteExtender using Google Suggest API

Hi,

After a long time I am posting an article.

This is on the Ajax toolkits control called AutoCompleteExtender.

Here I am trying to make a google suggest like site, using the Google Suggest REST API.

The Page will somewhat look like this:



The autocomplete extender works on the textbox and uses a webservice method. You need to have a webform (default.aspx), a webservice (google.asmx). Follwoing is the default.aspx page:
NOTE: I have used VS 2005 with AJAX extention and AjaxControlToolkit. Create a new Ajax enabled website from VS 2005. The dfault.aspx has nothing but 1 textbox, and the associated autocompleteextender:

Google Suggest:
asp:TextBox ID="TextBox1" runat="server"
asp:Button ID="Button1" runat="server" Text="Search" OnClick="Button1_Click"
cc1:AutoCompleteExtender
ID="AutoCompleteExtender1"
runat="server"
Enabled="true"
MinimumPrefixLength="1"
TargetControlID="TextBox1"
ServicePath="google.asmx"
ServiceMethod="getList"
/cc1:AutoCompleteExtender
______________________________default.aspx___________________________



____________________________________________________________________ You may give the code for Button1_Click:

protected void Button1_Click(object sender, EventArgs e)
{
string url = "http://www.google.co.in/search?hl=en&q=" + TextBox1.Text;
Response.Redirect(url);
}
____________________________________________________________
google.asmx has one method called the getList which returns an array fetched from the google suggest API.

_______________________google.asmx____________________________________


using System;
using System.Collections.Generic;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml;

///


/// Summary description for google
///

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class google : System.Web.Services.WebService
{
[WebMethod]
public string[] getList(String prefixText)
{
XmlDocument doc = new XmlDocument();
List suggArList = new List();
string url = "http://google.com/complete/search?output=toolbar&q=" + prefixText;
doc.Load(url);
foreach (XmlNode node in doc.SelectNodes("//CompleteSuggestion"))
{
string value = node.SelectSingleNode("suggestion/@data").InnerText;
suggArList.Add(value);
}
return suggArList.ToArray();
}
}
____________________________________________________________________

NOTE: there seems to be an issue when code behind system is used for the webservice, also we need to ensure that [System.Web.Script.Services.ScriptService] is called.