Skip to content
 

Book List App: Using Auto-Suggest with CodeIgniter

I had a couple fields on the form for adding authors/books to the DB for which I wanted to use an “auto-suggest” feature via JavaScript; one of those things where after you start typing it pops up a list of matching choices from which you can select the one you want. After trying several different scripts that I could not get to work for one reason or another, I ended up using Ajax Auto Suggest v.2.

I did, however, have to change one line of that JavaScript file in order to get it to play nicely with CodeIgniter “friendly” URLs. I just got rid of the bit that set a varname= part of the URL:

	// create ajax request
	//
	if (typeof(this.oP.script) == "function")
		var url = this.oP.script(encodeURIComponent(this.sInp));
	else
		// var url = this.oP.script+this.oP.varname+"="+encodeURIComponent(this.sInp);
		var url = this.oP.script+encodeURIComponent(this.sInp);

Then when activating it within the page (CI view), I simply specified the CI URL to the controller/function with a trailing slash, to which the JS script then appends the value which my CI method will receive as its first (and only) parameter:

<script type='text/javascript'>
// <![CDATA[
	var options = {
		script:"/index.php/ajax/author_auto_complete/",
		json:true
	};
	var as_json = new bsn.AutoSuggest('author', options);
// ]]>
</script>

One Comment

  1. Felix says:

    Indeed, AutoSuggest scripts can be hard to “import” and adapt to your own project, mainly because each project is unique. I wrote an AutoSuggest script from the ground up (well, using MooTools) for tastekid.com. Challenges included (well, besides the usual browser inconsistencies and cross-platformness) getting a non-standard response (well, it’s JSON, but formatted more weirdly), a more complex way of filtering results (e.g. if you type “Ra” it will also suggest “*The* Ramones”) and finding the right balance between javascript filtering of results and PHP filtering. Normally, PHP would return 20-some results, but javascript would display only 5 of them and keep filtering them as the user types. When it has less than two suggestions, it will make another request. It was a two-day job, but it was fun :)
    You can view the script (if you care) here (the site doesn’t include it, it uses a single cached and minified js file that contains everything).

Leave a Reply

You must be logged in to post a comment.