Sharemovi.es / make a cool multifunctional autocomplete

November
3rd,
2012

Today two posts about enhancements in Sharemovi.es. In this post I will show you how to make a multifunctional autocomplete box. In the next article I show you how to dynamically load in IMDB vote results for a particular movie.

Autocompletes are around for a long time, but I still love them for my apps. It makes the app flow faster and navigation can be much shorter not cluttering the page.

How it works

But if you prepend the search term with the "@" sign, for example "@be" it starts to find persons (actors/directors) and sharemovi.es users in the same search:

Implementation

This is an extension to the movie search interface with instant trailers I blogged about last year.

Autocomplete plugins work with AJAX: javascript calls a serverside script (PHP in this case) which returns its result in a certain format (JSON in this instance). Javascript digests this result and sticks it into the DOM.

The search term is sent from JS, if it starts with @ it performs a search against themoviedb and against the users in the sharemovies database. If no @ is prepended to the search, it does a regular movie search, again against themoviedb API. I could cache the results but for now the search box use seems within the themoviedb limits (I do cache movie and person pages though which reduces the amount of calls to the API significantly).

The $maxNumItems array restricts the number of items in the returned result so that the autocomplete result box fits reasonably well within the page.

The json_encode is run on the array of row arrays for JS consumption.

queryApi3 is a routine to query themoviedb API, I omitted it for brevity, interesting in more details, just drop me a line ...

The Javascript code to digest the result (after including the jQuery library):

source: "search.php" => here you see the backend PHP script being called.

.data( "autocomplete" )._renderItem => this consumes the elements returned by the PHP backend script. It wraps it in convenient HTML I styled with CSS (which exact styling is beyond the scope of this tutorial).

Note in the last part I overwrote some of the CSS rules of the autocomplete jQuery plugin to present smaller entries for person vs. movie results (see printscreens at the start of this post). The movie results give back more verbose data. So now each result takes up just the necessary space.

Some things are hardcoded like the sharemovi.es domain name and the handling of no results ("item.value.match(/^Oops/)") but that is fine for now.

This tutorial gives you a 90% jumpstart how to implement a rich multi-functional autocomplete. I hope it inspires you to build something similar. Also let me know if you have implemented a similar feature in any other language.