Click here to Skip to main content
Email Password   helpLost your password?

Dictionary

Introduction

This is an implementation of Google Suggest like dictionary in ASP.NET.

Background

After seeing Google Suggest, I was amazed and wanted to know how it worked. This project is just an experiment using the same technique that Google uses.

Using the code

The ZIP file consists of two files. One is an HTML file that uses the XMLHttpRequest object to make requests and get back data. The other one is a server script implemented in ASP.NET that connects to a SQL Server database. If you wish to implement a similar interface, just use the HTML functions provided. A proof of concept website could be accessed here.

How does it work?

The architecture could be explained as outlined below:

Concept

As you type a word in the textbox, a JavaScript event fires an HTTP GET request to the ASPX page. The response from the ASPX page is simply displayed in a div tag under the textbox. The page is not refreshed/reloaded for every keystroke as everything is done by the JavaScript in the page. The main JavaScript object that allows us to do this is XMLHttpRequest. You could read about it from Apple's developer site here. This is supported by IE 5.0 +, Mozilla 1.0 + and Apple's own Safari 1.2 +.

Database

The database contains just one table. The data comes from a freely available online dictionary (a public domain English word list dictionary, based on the public domain portion of "The Project Gutenberg Etext of Webster's Unabridged Dictionary" which is in turn based on the 1913 US Webster's Unabridged Dictionary. You could download it from here). The table is called WordList:

WordList
Word varchar(255)
Type varchar (10)
Meaning text

I created an index on "Word" column for speed. There are a total of 182696 words in the database.

ASP.NET page

The ASP.NET page is pretty straight forward. Gets the top 10 matching rows from the database and spits it out. Below is the code I am using (although SqlDataReader might be more appropriate):

<%@Page Language="C#"%>
<%@Import Namespace="System.Data"%>
<%@Import Namespace="System.Data.SqlClient"%>
<%@Import Namespace="System.Configuration"%>

<script runat="server">

    public void Page_Load(object sender,EventArgs args)
    {
        string keyword=Request["k"];
        if(keyword!=null  && keyword.Trim()!="")
        {
            string sql="select top 10* from WordList where" + 
                   " word like '"+keyword.Trim().Replace("'","''")+"%'";
            SqlConnection conn=new 
               SqlConnection(ConfigurationSettings.AppSettings["connectionString"]);
            conn.Open();
            DataTable dt=new DataTable();
            SqlCommand command=new SqlCommand(sql,conn);
            SqlDataAdapter adapter=new SqlDataAdapter(command);
            adapter.Fill(dt);
            conn.Close();

            foreach(DataRow row in dt.Rows)
            {
                string meaning=row["Meaning"].ToString();
                Response.Write("<strong>"+row["Word"].ToString()+"</strong> <i>");
                  Response.Write("row["Type"].ToString()+"</i>: "+meaning+"<br>");
            }
        }


    }

</script>

XMLHttpRequest object in the HTML page

<html>
    <head>
        <script>
var req;

function Initialize()
{
    try
    {
        req=new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch(e)
    {
        try
        {
            req=new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch(oc)
        {
            req=null;
        }
    }

    if(!req&&typeof XMLHttpRequest!="undefined")
    {
        req=new XMLHttpRequest();
    }

}

function SendQuery(key)
{
    Initialize();
    var url="http://www.objectgraph.com/dictionary/dict.aspx?k="+key;

    if(req!=null)
    {
        req.onreadystatechange = Process;
        req.open("GET", url, true);
        req.send(null);

    }

}

function Process()
{
    if (req.readyState == 4)
        {
        // only if "OK"
            if (req.status == 200)
            {
                if(req.responseText=="")
                    HideDiv("autocomplete");
                else
                {
                    ShowDiv("autocomplete");
                    document.getElementById("autocomplete").innerHTML = 
                                                      req.responseText;
                }
            }
            else
            {
                document.getElementById("autocomplete").innerHTML=
                    "There was a problem retrieving data:<br>" 
                    + req.statusText;
            }
        }
}

function ShowDiv(divid)
{
   if (document.layers) document.layers[divid].visibility="show";
   else document.getElementById(divid).style.visibility="visible";
}

function HideDiv(divid)
{
   if (document.layers) document.layers[divid].visibility="hide";
   else document.getElementById(divid).style.visibility="hidden";
}

function BodyLoad()
{
    HideDiv("autocomplete");
    document.form1.keyword.focus();

}
</script>
    </head>
    <body onload="BodyLoad();">
        <form name="form1">
        <input name="keyword" onKeyUp="SendQuery(this.value)" 
          style="WIDTH:500px" autocomplete="off">
            <div align="left" class="box" id="autocomplete" 
              style="WIDTH:500px;BACKGROUND-COLOR:#ccccff"></div>
        </form>

    </body>
</html>

The KeyUp event on the textbox triggers the SendQuery method. Note that we are disabling the auto-complete feature so it does not overlap with our div tag. The Initialize method creates the XMLHttpRequest object. In Mozilla and Safari, you could simply do this by using:

req=new XMLHttpRequest();

In IE, you could create the object based on the user's installation of MSXML libraries. The Process method acts as an event handler and displays the response text once the response is complete from the web server.

Observations

History

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
GeneralSo simple yet so powerful,,,
sevenlogix
6:23 22 May '09  
I've seen many implementations of Google Suggest that are way too complex and difficult to implement. The beauty of this example is in its simplicity. Great job!
GeneralGoogle Suggest like Dictionary
luckyroy
21:38 3 May '09  
hi,

This is lucky i have downloaded code from this link and added web config file and added appsetings in that and added connection sting in dics .aspx page but i am not getting any error are any result what i have to do sir can u reply me online plz mine is luckyroy29@gmail.com

http://www.codeproject.com/KB/aspnet/GoogleSuggestDictionary.aspx


Regards

Lucky
GeneralQuery Modification
Member 4505812
13:29 16 Dec '08  
Great article - thanks! However, I think your query should include ` ORDER BY Word` at the end of it, otherwise you don't necessarily pick up the top 10 items from the database. For example, just enter an `s` in your proof of concept website and the matches begin with `salt, surface, ...` whereas they should be `S, Saadh, Saan, ...'
GeneralProblem in "document.getElementById("autocomplete").innerHTML=req.responseText;"
4:01 10 Jan '07  
Hello Friends,
I download this project, and do some modifiations as per my requirement.
i changed only

var url="http://www.objectgraph.com/dictionary/dict.aspx?k="+key;
to--> var url=document.URL;
url=url+'?k='+key

and in code behind i written my code to get the values..
i get the values from database, but it will not showning the result in page, it will throughs "Unknown runtime error" on the line..
"document.getElementById("autocomplete").innerHTML=req.responseText;"
when write the stmt before this as

document.write(req.responseText);

then it will gives the actual result which is send from codebehind.
I am not able to findout the actual problem, why this code is not working..
why it will gives the error on

document.getElementById("autocomplete").innerHTML=req.responseText

Please tell me as early as possible

Thanks,
Mahadeo.

Questionselectable values in div tag
utsi
3:04 12 Oct '06  
Confused i noticed this in email sites(rediff.com,yahoo.com) where when u type name of person in the "to" textbox u get data in similar manner but u can also select values of the list availableOMG .when tab is press the values gets entered in the text box could please give a solution for this.
thks in advance.Cool
Generalget it working with access database???
wahabm
1:13 8 Aug '06  
Sigh
Hallo dear geniuses, Is there somebody who can use access database with .asp to get it working please. I have tried a lot without any success.
If you can do it please share it with us.
Thnx
Long life all geniuses.
Generalhow to display in listbox...
kamalika_kk
3:36 10 Jul '06  

can you please tell me how to display the top 10 search in a listbox so that we can select from the listbox and display records from database accordingly?.....actually i'm trying to develop a search technique as it is in the msdn help in any microsoft product....please can you help with this...?...i'm new in asp.net (1.1)......
GeneralPlease I need the database of this program
AMRSINAN
0:38 13 Jun '06  
Please I need the database of this program because the link bellow does not working
http://msowww.anu.edu.au/%7Eralph/OPTED/v003.zip

anybody share this file with me. Thnx
and thanks for this article, bro


MCSD Amr Sinan
Generaldatabase link died
masterbkhn
8:53 27 Apr '06  
http://msowww.anu.edu.au/%7Eralph/OPTED/v003.zip

anybody share this file with me. Thnx
and thanks for this article, bro Smile

-- modified at 13:53 Thursday 27th April, 2006
GeneralRe: database link died
piglet01
17:09 23 Sep '07  
If anyone was able to download this file I would like it also.

Thanks, Ann
GeneralAJAX creating problem on Local Site
eshna
21:41 16 Mar '06  
Hi
Sir:
i m getting the problem, infact can say m kid of confuse on the line
http://www.objectgraph.com/dictionary/dict.aspx?k[^]
that y r u using remote URL
as i also hav done the same work and i m also getting problem when i use the local site URL
it works fine with remote site URL but create problem on local site
such as if i m accesing a page from

url="http://www.objectgraph.com/dictionary/dict.aspx?k"
but if i use
url="http://localhost/dictionary/dict.aspx?k"
then it will not work

i m working with ASP
and another thing i have to use many controls on same page using ajax
as i hav already made a generic script for that purpose but even then it gives me error if i click on the list boc through mouse


waiting for early response
have a nice day
thanks & Regards,
Nazish Abbasi

GeneralRe: AJAX creating problem on Local Site
tejas_chonkar
23:21 23 Apr '06  
If you are getting HTML/Javascript error

do the following:

add another table on your web page as
'display:none'>
'tdResult'>

update the Process function

function Process()
{
if (req.readyState == 4)
{
// only if 'OK'
if (req.status == 200)
{
if(req.responseText=='')
HideDiv('autocomplete');
else
{
ShowDiv('autocomplete');
try
{
document.all.autocomplete.innerHTML = req.responseText;
}
catch(oc)
{
document.all.tdResult.innerText = req.responseText;
var iPos = document.all.tdResult.innerText.indexOf('#');

if(iPos>0)
document.all.autocomplete.innerHTML = document.all.tdResult.innerText.substring(0,iPos);
}
}
if(document.all.autocomplete.innerText=='')
HideDiv('autocomplete');
}
else
{
document.getElementById('autocomplete').innerHTML = 'There was a problem retrieving data: '
+ req.statusText;
}
}
}

change your code behind


foreach(DataRow row in dt.Rows)
{
Response.Write("" + row["Word"].ToString() + " ");
Response.Write(row["Type"].ToString() + "
: " + row["Description"].ToString() + "
");
}
Response.Write("#"); //new line of code

Some People succeed because they are Destined to, but most people succeed because they are Determined to
GeneralW2003K web server permissions
LeighG
2:28 12 Feb '06  
Hi
This is the answer to my problems for a predictive text lookup of db entries.
However it only works on the server from the downloaded zip file. I have tried to build what I want from the code but continually get line 39 permission denied.(req.open("GET", url, true);)[Like Amber but different] It seems that the security has me locked out. I gave the iusr guest account modify opermissions. No change. From the web page saved into the same folder (shared docs) I get system blocks at every letter and the predictive function does not work. Why does the zip folder work?
What I want to do is return the Lastname, firstname, and ID fields from a table....and I want to display the ID hyperlinked (twice) to 2 different asp pages. I am currently using VB.asp and a MySQL DB. Am I wasting my time?
NewsConverted code in vb.net
suri1971
22:25 30 Jan '06  
<%@ Page Language="vb" AutoEventWireup="false" Codebehind="WebForm5.aspx.vb" Inherits="NCart.WebForm5"%>
<%@ Register TagPrefix="ftb" Namespace="FreeTextBoxControls" Assembly="FreeTextBox" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML>
<HEAD>
<script>
var req;

function Initialize()
{
try
{
req=new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
req=new ActiveXObject("Microsoft.XMLHTTP");
}
catch(oc)
{
req=null;
}
}

if(!req&&typeof XMLHttpRequest!="undefined")
{
req= new XMLHttpRequest();

}

}


function SendQuery(key)
{
Initialize();
var url="Dt.aspx?k="+key;

if(req!=null)
{
req.onreadystatechange = Process;
req.open("GET", url, true);
req.send(null);
}
}


function Process()
{
if (req.readyState == 4)
{
// only if "OK"
if (req.status == 200)
{
if(req.responseText=="")
HideDiv("autocomplete");
else
{
ShowDiv("autocomplete");
//alert(req.responseXML);
document.getElementById("autocomplete").innerHTML =req.responseText;
}
}
else
{
document.getElementById("autocomplete").innerHTML=
"There was a problem retrieving data:
"+req.statusText;
}
}
}

function ShowDiv(divid)
{
if (document.layers)
document.layers[divid].visibility="show";
else
document.getElementById(divid).style.visibility="visible";
}

function HideDiv(divid)
{
if (document.layers) document.layers[divid].visibility="hide";
else document.getElementById(divid).style.visibility="hidden";
}

function BodyLoad()
{
HideDiv("autocomplete");
document.form1.keyword.focus();
}
</script>
</HEAD>
<body önload="BodyLoad();">
<form name="form1">
<input önkeyup="SendQuery(this.value)" style="WIDTH: 500px" name="keyword" autocomplete="off">
</form>
</body>
</HTML>


Suresh Kumar Thanda
Sr. Software Engineer
NewsCode in Vb.net
suri1971
21:59 30 Jan '06  
Public Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
     Dim keyword As String = Request.QueryString("k")
          If keyword.Trim <> "" And Not keyword Is Nothing Then
               Dim sql As String = "select top 5* from products where upper(ProductName) like '" + keyword.Trim().Replace("'", "''").ToUpper + "%'"
               Dim conn As String = ConfigurationSettings.AppSettings("NorthwindConnection")
               Dim da As New SqlClient.SqlDataAdapter(sql, conn)
               Dim tbl As New DataTable
               da.Fill(tbl)
               'style="WIDTH: 392px; Size = "5"
               Response.Write("<SELECT NAME='flavor' style='WIDTH: 500px'   Size = '10'>")
               For Each row As DataRow In tbl.Rows
                    Dim meaning As String = "<OPTION VALUE=" & row("ProductID") & ">" & row("ProductName").ToString()
                    Response.Write(meaning)
               Next
               Response.Write("</SELECT>")
          End If
     End Sub

Suresh Kumar Thanda
GeneralSorting a SubString Search
Fabito
3:14 24 Nov '05  
Hi Gavi Narra: I'm implementing a "Google Suggest" like text box for my application based on this article, that's great, I have done the following Store Procedure to retrieve the substring matches.

CREATE PROCEDURE [dbo].[GetSuggestShipper]
@Keyword nvarchar(60)
AS
SELECT top 10 ShipperId, ShipperName FROM Shipper WHERE ShipperName LIKE "%" + @Keyword + "%"
GO

In most cases, users will start typing the name they're looking for from the beginning, but not always that's why I don't use Type Ahead search LIKE @Keyword + "%" Now, I'd like to order the results based on the position of the substring, for example: Let's supose that there are 3 Shippers Called "UUUUABCDE", "ABCDE", "OOABCDE" and If the user types "ABC", the listing should be ordered in this way:
"ABCDE"
"OOABCDE"
"UUUUABCDE"
Is there anyway to do this?

Best Regards
QuestionCode behind does not work?
peterver
10:40 16 Nov '05  
The code works with inline coding, but doesn't work using code behind (javascript runtime error). Any idea why code behind doesn't work?

good
GeneralStatus 12029 when running code from client
Wegas
10:24 29 Sep '05  
Hi!

Thanks, great article! Your code runs perfectly when I run it on my server. When I try to run it from a client computer in the intranet, however, the request fails with status 12029. I first thought this might be a problem with proxy settings, but IE is set up to bypass proxy server for local addresses. Have you ever experienced something like this?
GeneralRe: Status 12029 when running code from client
MitchV
10:22 14 Feb '06  
I too had the same problem, but in my case it started on same machine, same configuration, after a reboot. Another reboot did not help. Please anybody help!
Generalproblem implementing in vb.net
saggimanoj
1:41 23 Sep '05  
I tried the same code to implement in vb.net using different table. I can't say whether it works with word database or not, but definitely id didn't worked with my database. I am giving the server side code here.

The html page seems to working fine, as I tried the same html page by changing the URL to objectworks site. The output was displayed correctly. I am sure that there is something missing in server side code.

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here
Dim keyword As String = Request("k").ToString()
If Not keyword Is Nothing And keyword.Trim() <> "" Then
Dim sql As String = "select Name from Table1 where" & " Name like '" & keyword.Replace("'", "''") & "%'"
Dim conn As SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings("connectionString"))
conn.Open()
Dim ds As DataSet = New DataSet
Dim command As SqlCommand = New SqlCommand(sql, conn)
Dim adapter As SqlDataAdapter = New SqlDataAdapter(command)
adapter.Fill(ds)
conn.Close()
For Each row As DataRow In ds.Tables(0).Rows
Dim meaning As String = ds.Tables(0).Rows.Item(0).ToString()
Response.ContentType = "text/html"
Response.Write("'" & ds.Tables(0).Rows.Item(0).ToString() & "'
")
Next row
End If
End Sub

Pleae tell me if I m wrong somewhere as it is very important for me to impelement this thing today. Any comments shall be highly appreciated by me. Looking forward to members help.
GeneralIts really nice article..great job
Surendra Sambana
20:16 4 Sep '05  
Infact i am looking for a spell check engine like what we have in gmail.
do u have any idea how to approach..i tried with soundex function but its not giving 100% acurate suggestions..please let me know if u have any idea.
Thanks and Regards
Surendra
GeneralHow to Change Source From Your Site
eebb2244
23:01 21 Aug '05  
I am trying to change the source of the feed from

var url="http://www.objectgraph.com/dictionary/dict.aspx?k="+key;

to my on database backend, e.g. SQL Server table with my own data. It seems that your (Gavi) code, no matter what is in the .aspx section, still runs from this domain, i.e. http://www.objectgraph.com/dictionary/dict.aspx[^]
How can I just to tell it read from my source?
GeneralMining Google Web Services: Building Applications with the Google API
Anonymous
21:48 21 Aug '05  
Mining Google Web Services: Building Applications with the Google API

the tutorial can be found in http://www.ebook5.com/ebook5details.aspx?productID=500&catid=1&subcatid=145[^]
GeneralGoogle Hacks: 100 Industrial-Strength Tips & Tools
Anonymous
3:53 14 Aug '05  
in http://www.ebook5.com u can find this and http://www.ebook5.com/readingeBook5.aspx?productID=332&catid=1&subcatid=137&pageno=2[^]

http://www.ebook5.com/ebook5details.aspx?productID=315&catid=1&subcatid=131[^];P
Generalnot able to host the page
iomca4u
19:14 6 Aug '05  
hi,
when i try to host the page, a javascript error is thrown stating :
permission denied. However, the same code is working fine in localhost.
Thanks in advance

Amber.


Last Updated 27 Dec 2004 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010