It seems the documentation for this JQuery autocomplete plugin isn’t uptodate. Using a remote JSON call is actually easier that you might think from reading the docs.
In this example i’m using a Grails controller class called KandidaatController. It contains one method to find Kandidaat objects having a lastname starting with the entered string. The objects found are returned in JSON format.
def searchByNaam = {
def kandidaat = Kandidaat.findAllByAchternaamIlike(params.q + "%")
if ( kandidaat ) {
render kandidaat as JSON
} else {
response.sendError(400, "Kandidaat niet gevonden");
}
}
This method is made available as a REST service using the following configuration in UrlMappings:
"/kandidaat/naam/$q?"(controller:"kandidaat"){
action = [GET:"searchByNaam"]
}
Enabling autocomplete on an input field looks like the code below. You need to specify the url of your rest service, and specify that you are using JSON. Using the function parse you need to parse the received JSON data and return an array containing objects for every row to be displayed. Every object in this array contains three properties: data (all the data for the row), value (just the value displayed), and result (the formatted value). I found that i also needed to implement formatItem, which returns the value as displayed in the autocomplete dropdown list.
$("#zoekKandidaat_naam").autocomplete(
// rest url
"kandidaat/naam"
, { dataType:"json"
, formatItem: function(data,i,max,value,term){
return value;
}
, parse: function(data){
var acd = new Array();
for(var i=0;i<data.length;i++){
acd[acd.length] = { data:data[i], value:data[i].achternaam, result:data[i].achternaam };
}
return acd;
}
}
);
Maybe it’s possible to do this with even less code, but i’m really impressed by what you can do with JQuery and Grails.

September 17th, 2009 at 15:41:38
[...] Using JQuery autocomplete with Grails and JSON In this example i’m using a Grails controller class called KandidaatController. It contains one method to find Kandidaat objects having a lastname starting with the entered string. The objects found are returned in JSON format. [...]
September 28th, 2009 at 14:48:49
thanks, exactly what i was looking for
One thing i noticed is that it doesn’t work with special characters (like a german ö or a french è). Any idea how to change that?