473,574 Members | 2,249 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problem with Type-Ahead

I'm having a little problem with using type-ahead functionality for an
auto-suggest box. Sometimes, when I start to type something and the
type-ahead shows up, the AJAX will send a request query using the value
that *includes* the type-ahead value. In other words, say that I type
in "ja" and the first listing that comes up is "ja**@test.com" . The
AJAX part is supposed to send "ja" as one of the query string variables
when calling the remote file (using the GET method); this way, the
response from the remote script should be all the listings that start
with "ja". BUT, for some reason, sometimes the query string that is
sent *includes* the type-ahead value, so instead of sending just "ja",
it will send "ja**@test.com" , and consequently, narrow the search down
to this one listing. I'm assuming this is some sort of synchronization
problem (XmlHttpRequest being asynchronous), but I haven't been able to
figure it out.

Here is the code that executes for the keyup event of a legitimate key
(excluding keys like Shift, Home, etc.):

[------------------------------------------------------------------------
function doSuggest() { getSuggest(db_t able_name, db_column_name,
element(input_b ox_id).value, max_listings); }

timeoutID = window.setTimeo ut(doSuggest, 250);
--------------------------------------------------------------------------]

And here's the getSuggest function:

[--------------------------------------------------------------------------
function getSuggest(db_t able_name, db_column_name, db_search,
max_listings) {
if (!isWorking && http) {
var randomNumber = Math.floor(Math .random() * 9999999);
var url = "../get_suggest.php " +
"?r=" + randomNumber+
"&db_table_name =" + db_table_name +
"&db_column_nam e=" + db_column_name +
"&db_search =" + db_search +
"&max_listings= " + max_listings;

http.onreadysta techange = handleHttpRespo nseXML;
http.open("GET" , url, true);
//By the way, I've tried swapping the
above 2 lines, but this doesn't seem to make a difference.

isWorking = true;
http.send(null) ;
}
}//end function getSuggest
--------------------------------------------------------------------------]

Finally, here's the handleHttpRespo nseXML code:
function handleHttpRespo nseXML() {
if (http.readyStat e == 4) {
if (http.status != 200) {
alert("ERROR ON REMOTE SCRIPT! " + http.status);
return false;
}
if (http.responseT ext.indexOf('in valid') == -1 && http.status
== 200) {
var xmlDocument = http.responseXM L;

var num_rows =
xmlDocument.get ElementsByTagNa me('num_rows')[0].firstChild.dat a;
if(num_rows < 1) {
hide('suggest_b ox');
} else {//(num_rows >= 1)

var listings =
xmlDocument.get ElementsByTagNa me('output')[0].firstChild.dat a;

num_listings = num_rows;

document.getEle mentById('sugge st_box').innerH TML = listings;
show('suggest_b ox', 'inline');

//Reset listing_number back to 1 and highlight it.
listing_number = 1;
highlight('list ing1');

//----------- TYPE-AHEAD ------------//
//If user pressed backspace or delete, don't do type-ahead.
if (key == BACKSPACE || key == DELETE) {
//Ignore.
} else {
//Show the first listing (which is the closest match) in the
//textbox, highlighting the part the user has not typed.
//First, get length of the text currently in textbox.

var charLength =
document.getEle mentById(input_ box_id).value.l ength;

//Next, show the listing in the search box.
document.getEle mentById(input_ box_id).value =
document.getEle mentById('listi ng1').innerHTML ;

//Finally, highlight everything in the search box
//after what the user had originally typed:

highlightRange( input_box_id, charLength);
}//end type-ahead block
}//end else (num_rows >= 1)

isWorking = false;
}
}
}//end function handleHttpRespo nseXML

I guess I need to include the highlightRange function, too:

[-----------------------------------------------------------------------
function highlightRange( elem, start, end) {
var textbox = document.getEle mentById(elem);
charLength = textbox.value.l ength;

switch (arguments.leng th) {
case 1:
start = 0;
end = charLength;
break;
case 2:
end = charLength;
break;
}//end switch

if (textbox.create TextRange) {
var range = textbox.createT extRange()
range.moveStart ("character" , start);
range.moveEnd(" character", end);
range.select();
} else if (textbox.setSel ectionRange) {
textbox.setSele ctionRange(star t, end);
}
}//end function hightlightRange
------------------------------------------------------------------------]

Alright, so again, I know it's probably a synchronization problem.
I've tried using setTimeout, but this isn't going to solve the problem.
Also, I've found out exactly when the problem occurs. Using the same
example, let's say that "ja**@test. com" is the first listing that comes
up for "ja". And let's say that I'm looking for something starting
with "jas". Now, the problem occurs exactly in the following timing: I
type "ja" quickly, wait a split second and then *right before*
"ja**@test. com" shows up, I type in an "s" - but the result from typing
the "ja" ("ja**@test.com ") shows up and overrides the "s" I just typed
in. Any ideas on how I can fix this problem (or synchronize the AJAX
properly)?

Nov 23 '05 #1
12 5118

Joel Byrd wrote:
I'm having a little problem with using type-ahead functionality for an
auto-suggest box. Sometimes, when I start to type something and the
type-ahead shows up, the AJAX will send a request query using the value
that *includes* the type-ahead value. In other words, say that I type
in "ja" and the first listing that comes up is "ja**@test.com" . The
AJAX part is supposed to send "ja" as one of the query string variables
when calling the remote file (using the GET method); this way, the
response from the remote script should be all the listings that start
with "ja". BUT, for some reason, sometimes the query string that is
sent *includes* the type-ahead value, so instead of sending just "ja",
it will send "ja**@test.com" , and consequently, narrow the search down
to this one listing.
[snip]
function doSuggest() { getSuggest(db_t able_name, db_column_name,
element(input_b ox_id).value, max_listings); }
Here you are sending the value of the text input to the getSuggest
function. This would include the lookahead that was placed into the
text input by:
[snip]
//Next, show the listing in the search box.
document.getEle mentById(input_ box_id).value =
document.getEle mentById('listi ng1').innerHTML ;
So either don't put the entirety of the suggestion into the text input
or don't send the selected portion of the text input to the getSuggest
function.
Alright, so again, I know it's probably a synchronization problem.


Nope. It's doing exactly what you're telling it to. It doesn't have
anything to do with the AJAX. OT: You should consider using key events
instead of a timer. There's no need to make a roundtrip to the server
if the user hasn't typed anything.

Nov 23 '05 #2
But with the autocomplete, when I type a letter, any existing
type-ahead characters automatically disappear, so that at that moment,
what is in the input box is only what I have typed, and it is at that
point that I call the getSuggest function, which queries the database
with the current value of the input box, and *then* based on the
results, creates the type-ahead characters. So, I don't see how the
type-ahead characters could get sent to the database since the sequence
of actions is what I just described. Even so, I know the type-ahead
characters sometimes *are* being sent to the database. So, again, I
think it's some sort of synchronization problem (I don't pretend to be
any kind of javascript expert, so I certainly could be wrong about this
- I'm just trying to understand it). In summary, the sequence of the
code is the following (we'll assume user has already typed some letters
so that there is already some type-ahead text highlighted):

1) User types a letter.

2) On keydown, the highlighted type-ahead text disappears so that now
all that appears is what the user has typed.

3) On keyup, the autosuggest function is called:
getSuggest(db_t able_name, db_column_name,
document.getEle mentById(input_ box_id).value, max_listings).

4) The XmlHttpRequest object is used to query the database with the
current value of the input box (which *should*, at this point, be only
what the user has typed (see step 2).

5) Results come back from this query, populating the drop-down suggest
box and populating the input box with the first result, highlighting
what the user has not typed.

Dec 1 '05 #3
In fact, I just did some testing and realized that I am having the same
problem even *without the type-ahead* functionality, so the type-ahead
is not the problem.

Dec 1 '05 #4
VK

Joel Byrd wrote:
In fact, I just did some testing and realized that I am having the same
problem even *without the type-ahead* functionality, so the type-ahead
is not the problem.


I did not look your code through (it's big :-)

Just for hell of it:

instead of:
var randomNumber = Math.floor(Math .random() * 9999999);

try:
var randomNumber = (new Date()).getTime ();

Dec 1 '05 #5
Joel Byrd wrote:
But with the autocomplete, when I type a letter, any existing
type-ahead characters automatically disappear, so that at that moment,
what is in the input box is only what I have typed, and it is at that
point that I call the getSuggest function...


It would be helpful to see all the code and the markup involved. Do you
have it uploaded somewhere? Otherwise we are making suppositions about
things we cannot see. I assumed you were using a timer but you are
using key events.

Dec 2 '05 #6
> It would be helpful to see all the code and the markup involved. Do you
have it uploaded somewhere?


Right, of course. I've copied it over to my personal school webspace.
So here's the address: http://web.njit.edu/~jmb2/Joel/suggest.php

Dec 6 '05 #7

Joel Byrd wrote:
It would be helpful to see all the code and the markup involved. Do you
have it uploaded somewhere?


Right, of course. I've copied it over to my personal school webspace.
So here's the address: http://web.njit.edu/~jmb2/Joel/suggest.php


OK. Some testing shows that the network lag is causing the poor
behavior. I type "ang" quickly and then it was replaced with "Aaron
Patterson" with the "on Patterson" selected. So the result was from the
first "a" typed. But it still respected the fact that I had typed 3
characters when it did the selection routine.

I think you can solve the issue if you'll cancel all previous requests
on keydown. Then what the user types will never be replaced and only
the last keyup will be an active request. Thoughts?

Dec 6 '05 #8
That thought had actually crossed my mind. Any suggestions on how to
actually cancel a previous request?

Dec 7 '05 #9

Joel Byrd wrote:
That thought had actually crossed my mind. Any suggestions on how to
actually cancel a previous request?


Most xmlhttp implementations have an "abort" method which you could
call to cancel the processing. Just keep the previous request
referenced by a variable and call the abort method on that variable
when a new request is made. Should be simple...

Dec 8 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
2341
by: Jeff Dunnett | last post by:
Hello, I have written the following HTML Form: <html><head><title>Survey</title></head> <body bgcolor="black" text="white" link="#f6b580" vlink="#c0c0ff"> <img src="logo.gif" width="324" height="104"alt="logo.gif (15760 bytes)"><br><br> <table border="0" cellpadding="0" cellspacing="0" width="307" align="left">
9
2331
by: rbronson1976 | last post by:
Hello all, I have a very strange situation -- I have a page that validates (using http://validator.w3.org/) as "XHTML 1.0 Strict" just fine. This page uses this DOCTYPE: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> When I change the DOCTYPE to (what should be the...
2
5425
by: Praveen K | last post by:
I have a problem in communicating between the C# and the Excel Interop objects. The problem is something as described below. I use Microsoft Office-XP PIA dll’s as these dll’s were been recommended by many for web applications. I create the instances of Excel, Workbook and the worksheet. And later on Release the references by...
2
2743
by: yqlu | last post by:
I hava developed a client in C# that is connected to a 3-party XML Web Services developed in Java based on the AXIS 1.1. Most methods call are successful except for one method named "findObjects" and return a complex type "FieldSearchResult". The error message as following : "Cannot assign object of type System.String to an object of type...
5
19573
by: Stacey Levine | last post by:
I have a webservice that I wanted to return an ArrayList..Well the service compiles and runs when I have the output defined as ArrayList, but the WSDL defines the output as an Object so I was having a problem in the calling program. I searched online and found suggestions that I return an Array instead so I modified my code (below) to return...
5
13197
by: rocknbil | last post by:
Hello everyone! I'm new here but have been programming for the web in various languages for 15 years or so. I'm certainly no "expert" but can keep myself out of trouble (or in it?) most of the time. This particular problem has plagued me for years; it is making me very, very, old. :-( It deals with the way Javascript's method of floating point...
5
1769
by: Nightfall | last post by:
Dear friends, consider the following scenario, in Visual Studio 2005 and C# - I create a ASP.NET web service ("server") with a class MyClass and a WebMethod SomeMethod() - I create a client application, using "Add web reference..." and specifying some web reference name "MyName" Normally I would do:
2
2260
by: Ravi Joshi | last post by:
The menu on my site works fine in IE6 and Firefox. In IE7, there is a problem with the menu: when you mouse over the various main catagories, the sub-catagories all appear to the right as they should; however, as soon as you mouse towards any but the TOP sub-catagory, all those sub-catagories still view there. It will work first time quite...
2
3139
by: swethak | last post by:
Hi, I am getting the problem the problem with google map in Internet Explorer. This map worked fine in mozilla . When i opened the same map in Internet Explorer i am getting the error message as in alert box as " Internet Explorer cannot open the Internet site http://google.citycarrentals.com.au/viewalllocations.php . Operation...
4
2938
by: liberty1 | last post by:
Hi everyone. I appreciate your effort at helping newbies like me. I have the following problems and will appreciate urgent help. PROBLEM NUMBER 1: Using PHP and MySQL, I am able to upload picture successfully unto the server but not so with the file name of the picture even though other parameters in my form got inserted successfuly in the...
0
7801
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, well explore What is ONU, What Is Router, ONU & Routers main...
0
8044
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8229
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7808
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6450
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development projectplanning, coding, testing, and deploymentwithout human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5299
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3749
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1335
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1055
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.