I use this for a webshop form:
Controller:
function productajaxsearch(){
if(isset($this->request) && $term = $this->request->getVar('term')){
$where = "Title LIKE '%" . (string)$term . "%' OR SubTitle LIKE '%" . (string)$term . "%' OR Content LIKE '%" . (string)$term . "%'";
if($products = DataObject::get('Product', $where)){
$return_arr = array();
foreach($products as $p){
$array['link'] = $p->Link();
$array['title'] = $p->Title;
$array['image'] = '<img src="'.$p->Image()->SetWidth(50)->Link().'" />';
array_push($return_arr,$array);
}
return json_encode($return_arr);
}
}
}
jQuery autocomplete code:
var div = document.getElementById('SearchForm_ProductSearchForm_Search');
if (div !== null){
var cache = {};
$( "#SearchForm_ProductSearchForm_Search" ).autocomplete({
minLength: 2,
source: function(request, response) {
if ( request.term in cache ) {
response( cache[ request.term ] );
return;
}
$.ajax({
url: "Page_Controller/productajaxsearch",
dataType: "json",
data: request,
success: function( data ) {
cache[ request.term ] = data;
response( data );
}
});
}
}).data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( '<div class="searchitem">' + item.image + '<div class="searchtitle"><a href="'+item.link+'">' + item.title + '</a></div><div class="clear"></div></div>' )
.appendTo( ul );
};
}