views:

106

answers:

2

Hi SO,

What I'm currently doing is using jQuery to perform an ajax request on every keypress. So if my user typed d-o-n-k-e-y, it would send one request for each letter. However, since they take different paths to the server on the network, if they type d-o-n-k-e-y too fast, they don't always arrive in order. They might arrive as D-n-o-k-y-e, and react accordingly. Is there a good way to make sure all the requests get sent in order?

I don't think waiting for confirmation from a request before sending the next one would work, because it would slow the information transfer so much. Does anyone have any ideas?

Thanks.

+7  A: 

From: http://api.jquery.com/jQuery.ajax/

async boolean
Default: true

By default, all requests are sent asynchronous (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.

Also, it may not be the best idea to send an ajax request every single keystroke. Can't you use a timeout and send a don and key request (buffered up to every 300 ms for example)?

ChristopheD
That's an awesome idea. Thanks!
Ethan
+1 for suggesting buffering and delay.
Michael Aaron Safyan
A: 

Here are some ideas-

  • Cancel your old requests as new ones are made. This will minimally reduce load to the server and achieve what you ask.

  • Instead of making your server keep track of which requests came when, it would only take a small helper object to keep track of which is the latest request. var mostRecentRequest = XHR({ success: function() { if( this === mostRecentRequest ) { ... } } });

  • As mentioned above, only make a call to the server when the user stops typing for a moment. Do a setTimeout() on keyup that fires ~500ms later and sends the request, and cancel and reset that timeout each time a new key is pressed.

Do NOT do synchronous XHR requests in the browser. Ever. Under any circumstance. The entire browser will hang until the request is completed, which could be as much as a couple of seconds.

Alex Forster