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!
My suggestion would be have the autocomplete perform the
$.get()based on a timer. When a user performs akeyup, start a timeout (say 1sec for arguments sake) which when finished, triggers the update. On thekeydownevent, 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/