Musings of a Fondue

JResig Book - AutoComplete

Original Date: February 18, 2014

In chapter 12 of his book Pro JavaScript Techniques, John Resig walks through how to create an autocomplete search using AJAX.

Here’s my go at it1

User Interface

The UI was fun to work on. Okay, maybe not all the time. But the end product was rewarding.

As seen in the book,

My take on it,

Server code

The autocomplete search relies on a file called auto.cgi being called and executed as the user types. For example when the user types “c”, a request is sent to the server for auto.cgi?to=c. The server executes auto.cgi with c as the argument, returning all the users whose names contain the letter c.

As the user continues to type, auto.cgi is called with the new arguments. For example typing “ca” calls auto.cgi?to=ca, typing “cat” calls auto.cgi?to=cat and so on.

The auto.cgi code provided in the book was written for Perl. I had Ruby and Python installed on my computer and I was somewhat familiar with the languages. I didn’t want to install and learn Perl just for this one-off project. So, I ended up rewriting auto.cgi. First to Ruby, then to Python as I could not get the built-in Ruby server to serve CGI files.

The code,

  • original in Perl
  • rewrite in Ruby
  • rewrite in Python

Even though Python has a dedicated CGI server, it didn’t work with my program (I’m not sure why). After a lot of searching, I eventually came across this tutorial and server script. With it the program finally worked!

On Reflection

I’m not sure if Resig did this intentionally, but copying and pasting the code as it appears in the book does not work. By the time you figure out what you need to add/edit/delete to make it work, you have pretty much learned how it works and more than you bargained for!

The final code can be found on Github.

Update (November 2015):

1 When uploading this post to the blog, I also wanted to upload the program so people could try it out. I suspected that if I had that much trouble getting the CGI file to work locally, getting it to work on another server would be a challenge. Haha. Little did I know just how deep the rabbit hole would be. Here’s a link to a post where I emerge out of the rabbit hole (warning - time travel).

Comments