Prevent slow data in AJAX (abstract concept thereof)

UPDATE 1/29/11 I’ve since found a simpler solution to this problem and have a real working code example about it in this post: Prevent stale AJAX data in jQuery.

So at work I noticed an off bug in one of my old ajax scripts (on of my first in fact). The script may receive an older result after it has received a newer one (because it’s for some reason or another that command processed slower than the one after it). This is only really an occurrence when a script makes lots of requests in a row, for instance a live typing search result (ala google instant). This problem never occurred before with the faster scripts using a smaller test base, and if fact wouldn’t be a problem if I had a button to press to activate the script, instead of the onkeyup event. Thats the simple solution, but not the nice looking one. I’ve though of a solution, and I’m sure there are a bunch more, and better, methods to achieve the same thing and if I think of a better one I’ll post it.

Okay so the concept of this (which at this time is only a concept because due to the nature of the problem, it’s not the simplest thing to test locally, but I will do so soon, probably tomorrow) is to get the timestamps of the data back and compare them again the curent one. Now I usually have the AJAX script call back pre-formatted code ready to be plopped into the page where needed, so in such a case you need to send the data and the time as two separate variables, probably via json because it’s simple and effective for this sorta thing. For the time sent back the simplest way would be seconds since epoch since the newer the entry the bigger then number leaving a simple greater than check, if it’s bigger then display the results and update the time, of not then you discard the data and the time.

That method should work great for determining if the data coming from the server is old, if your sending it from the script to a server and also want the newest of the new then it’s even easier. have javascript get the time (getTime() would work) and have it have it to the db, simple having the script compare those timestamps to each other before writing to make sure that for whatever reason (although unlikely going in this direction). One this to remember if you also having PHP write this timestamp is that the javascript function will return the time in milliseconds, the PHP time() function returns time is seconds since epoch. Conversion will have to be made accordingly (and to be safe, round the javascript time down by dividing it by 1000 and flooring the number)

I’ll update this one I’ve actually done a real work test, but nothing in here seems like it’s going to cause any problems in implementation.

One Reply to “Prevent slow data in AJAX (abstract concept thereof)”

Leave a Reply

Your email address will not be published. Required fields are marked *