Steve
Steve

Reputation: 4566

Railscast doesn't recommend a solution for production, I'm looking for a reason why

In this railscast our good friend Mr. Bates walks through a solution to creating an app that can search, sort, and paginate a set of data. When going through AJAX searching he provides a solution that will display results of the search the moment a user enters input into the search box. Here is his solution:

$('#products_search input').keyup(function () {
  $.get($('#products_search').attr('action'), ↵ 
    $('#products_search').serialize(), null, 'script');
  return false;
});

However he states "Note that this is only a quick demo and isn’t the best way to do this. There are several jQuery plugins that you can use if you do something like this in a production app." I'm looking for an explanation on why he believes this isn't suitable for production. Thanks in advance!

Upvotes: 0

Views: 131

Answers (1)

Gazler
Gazler

Reputation: 84160

There are two major issues I see with this solution. The first is that you are making an HTTP (AJAX) request every time a key is pressed, which will not be the most efficient way of doing this. The second is that you are basically calling eval in the response, and eval is bad as it can lead to malicious users executing code you don't want to be executed.

Some suggestions on improving:

  • Use a proper JSON parser and pass the data back as JSON. (you can use $.getJSON)
  • Throttle the request - don't do it on every keyUp, maybe start a timer and only submit the request if no keys have been pressed in the last second, meaning it won't make lots of calls for people who type fast.
  • Cache the response. If you have already searched for something, then there is no point fetching the data twice. Keep a note (in a JS Object) of previous calls in this session and their results.

Upvotes: 1

Related Questions