The script.aculo.us Ajax.Autocompleter is basically a generic version of Google suggest. There is an excellent demo online.

But, some times the criteria you send to the server changes as the page state changes. I’ll describe a very common scenario that I encountered yesterday. I had a list of email addresses for a webmail client I maintain for work. Users don’t want to see addresses suggested, that they already put in their to field.

When I construct the Autocompleter, the to field is empty. You can pass the contents of the to field to the server, but if you did:

parameters: Form.Element.serialize(”to”)

You will always get to= because that is what it evaluates to when you construct the Autocompleter. The problem became obvious almost immediately, but the solution took me a little time to figure out. Fortunately, after diving into the code, I found what I needed already existed. You need to pass an option to the constructor called callback. This poorly named option gets called right before every Ajax server request. This expects you to return a parameter string that gets sent to the server. Here is a sample implementation.

callback: function(element, entry) { return entry + “&” + Form.Element.serialize(”to”); }

This snippet would be included as an option on the Ajax.Autocompleter constructor call. Your responsibility when implementing this, is to pass along the second parameter, entry, plus any dynamic content. You can assume you never have to muck with the entry parameter. In this example we are just doing a Form.Element.serialize on the to form field. Theoretical output would be to=fake@user.com, but it would change as you added more and more addresses to the to field.

Post Information

Tags:

We're Reading

Feeds/Syndication

17 Responses to “Ajax.Autocompleter && Dynamic Parameters”

Leave a Reply