I know the thread is old but it helped me a lot. I have this code:
http://pastebin.com/G75CFDxc
But the code does two queries and loads the ajax php script two times before going to the time out...