Zera42
Zera42

Reputation: 2692

Most efficient search method using AJAX?

Ok, so I'm starting to work on a search feature of my site, and I started to code it, and I realized mid way through that there would be a lot of overhead if say 100 people search for something at the same time. And since my ajax could would be called every keyup that would mean that for those 100 people, every time they typed something in the search box, it would run a query which I'm pretty sure is pretty inefficient.

So, I decided it would be better to make a cron job and have it run a script which runs and fetches all the rows from my database every 10-20 mins, and creates a JSON file. With that, my ajax call would now be to a file containing all the results that have been pre-fetched. And then with that, I find the search matches.

I was wondering if there is a more efficient or better way of doing this?

Upvotes: 0

Views: 234

Answers (2)

zedecliff
zedecliff

Reputation: 84

Making auto_complete faster

  1. Turn on gzib compression in ajax response to reduce the response size
  2. add indexes on columns used in search query
  3. add caching header in ajax to reduce the number of requests to the web server, the cache should have a convenient expiration time
  4. add server caching on most popular recent requests to reduce the number of database connections
  5. use fully constructed HTML as an ajax response instead of json data to prevent browser from reconstructing html DOM

Upvotes: 1

GrahamTheDev
GrahamTheDev

Reputation: 24825

What I would recommend is to add a simple delay to your calls between each key-up.

I use 250ms as that is a reasonable amount of time between key presses.

On each key press you start your timer and restart it at each key-press - calls are then made in the timer function.

//pseudo code

on key press - start timer function - pass in current letters

if key pressed - reset timer function - pass in current letters

key not pressed for 250ms - function runs to timer end - fire off ajax call.

This is the best balance between efficiency, useability and maintaintability - your JSON file would soon become unmanageable if your site grew (along with data transfer quantity etc.)

Upvotes: 2

Related Questions