views:

23

answers:

2

Hi guys,

I'm having some problems with an ajax autocomplete field. I did the same thing before but never ran into problems as I never really had a slow internet connection.

I have an input box which acts as an auto-complete field. I binded a jQuery keyup() event to that field and I'm querying a php file with each keypress on that field, returning a list of 20 matching elements. Altough the return data has only ~2-3kb at most, if I start typing faster, sometimes calls don't return in the order they were called.

Say I'm searching for "stackoverflow". It happens sometimes that the final list I get when I already typed "stack" is "st" which would bring more matches than needed. Is there any way to make sure the last call I get is the actual final one?

What I was thinking of was making sure the new data is smaller or at least equal to the data I has before, but I'm thinking this would be to much.

The data I'm querying comes from the Facebook Open graph, namely a json object like http://graph.facebook.com/100000530820249/friends (if you have a Facebook account, you could try http://graph.facebook.com/me/friends if you need authentification for my list).

I really need to fetch the data server-side for some processing so a purely JS method is out of the question. The solution should work for only making sure ajax calls don't overlap...

Thanks in advance everybody!

+1  A: 

The simplest approach is to have JavaScript pass a counter to your server-side script, and have the script simply pass the exact same value back in its result. Then JavaScript can check incoming results to see if the counter matches the current (i.e., most recent) value. If it doesn't, take no action; it's necessarily old data.

VoteyDisciple
Altough it's a good solution, it really didn't fit my needs, will keep it in mind tough. Thanks!
Claudiu
+1  A: 

My suggestion would be have the autocomplete perform the $.get() based on a timer. When a user performs a keyup, start a timeout (say 1sec for arguments sake) which when finished, triggers the update. On the keydown event, cancel the timeout. This means that if the user is typing quickly then it will only trigger when they stop/pause.

I'll admit this is not ideal, but it should get you on the right track.

Also, another option is to use the jQueryUI AutoComplete widget: http://jqueryui.com/demos/autocomplete/

Alastair Pitts
Thanks for the tip, sounds like a great idea! I'll try to implement it and get back to you with the results. I didn't want to load jQueryUI only for this, and even if I would, there are a lot of customizations to be done if I wanted to adapt it to what I need.
Claudiu
Worked as a charm, elegant solution. Thank you for the tip!
Claudiu
@Claudiu: Awesome! I wasn't sure exactly how well it would work, but it seemed sound in theory.
Alastair Pitts