473,385 Members | 1,320 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

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_table_name, db_column_name,
element(input_box_id).value, max_listings); }

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

And here's the getSuggest function:

[--------------------------------------------------------------------------
function getSuggest(db_table_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_name=" + db_column_name +
"&db_search=" + db_search +
"&max_listings=" + max_listings;

http.onreadystatechange = handleHttpResponseXML;
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 handleHttpResponseXML code:
function handleHttpResponseXML() {
if (http.readyState == 4) {
if (http.status != 200) {
alert("ERROR ON REMOTE SCRIPT! " + http.status);
return false;
}
if (http.responseText.indexOf('invalid') == -1 && http.status
== 200) {
var xmlDocument = http.responseXML;

var num_rows =
xmlDocument.getElementsByTagName('num_rows')[0].firstChild.data;
if(num_rows < 1) {
hide('suggest_box');
} else {//(num_rows >= 1)

var listings =
xmlDocument.getElementsByTagName('output')[0].firstChild.data;

num_listings = num_rows;

document.getElementById('suggest_box').innerHTML = listings;
show('suggest_box', 'inline');

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

//----------- 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.getElementById(input_box_id).value.length ;

//Next, show the listing in the search box.
document.getElementById(input_box_id).value =
document.getElementById('listing1').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 handleHttpResponseXML

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

[-----------------------------------------------------------------------
function highlightRange(elem, start, end) {
var textbox = document.getElementById(elem);
charLength = textbox.value.length;

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

if (textbox.createTextRange) {
var range = textbox.createTextRange()
range.moveStart("character", start);
range.moveEnd("character", end);
range.select();
} else if (textbox.setSelectionRange) {
textbox.setSelectionRange(start, 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 5098

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_table_name, db_column_name,
element(input_box_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.getElementById(input_box_id).value =
document.getElementById('listing1').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_table_name, db_column_name,
document.getElementById(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
Perfect! I didn't realize there was an abort method (I should have
just googled the xmlHttpRequest object). I put an abort statement in
the keydown handler function, and...it seems to have solved the problem
- thanks!

Dec 9 '05 #11
hehe, well it seems to have worked on my school site, but not on
another one I tried it on. Something having to do with the network
response, I don't know.

Dec 9 '05 #12
On 2005-12-07, Joel Byrd <jo******@gmail.com> wrote:
That thought had actually crossed my mind. Any suggestions on how to
actually cancel a previous request?


arrange to ignore the data it returns
or cancel it's onReadyStateChange handler
there may even be a way to close it.

but first you'll need a way to address it.

--

Bye.
Jasen
Dec 9 '05 #13

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

Similar topics

6
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"...
9
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...
2
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...
2
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"...
5
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...
5
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....
5
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...
2
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...
2
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...
4
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...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.