Currently trying to implement an autocomplete on a clients website which searches through products and textpages. For this, I’ve made a generic handler that returns anonymous objects as JSON. My anonymous object looks like this:
new
{
Name = product.Name,
Url = product.Url,
ImageUrl = imageUrl
});
The list of objects gets serialized with a standard .NET JavascriptSerializer.
And my javascript looks like this:
searchField.autocomplete({
source: "/handlers/SearchHandler.ashx",
response: function (event, ui) {
...
}
});
I’m a bit stuck when it comes to getting the values from JSON into the autocomplete dropdownbox though. Also, I want to use the results as links, so when the user clicks on a result in the dropdown, he/she gets redirected to the page/product.
Does anyone know how to achieve this?
Solution:
searchField.autocomplete({
source: "/handlers/SearchHandler.ashx?nodeId=" + currentNodeId,
search: function (event, ui) {
searchField.css("background-image", "url('../img/ajax-loader-small.gif')");
},
response: function (event, ui) {
searchField.css("background-image", "");
}
}).data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li>")
.data("ui-autocomplete-item", item)
.append("<a href='" + item.Url + "'>" + item.Name + "</a>")
.appendTo(ul);
};
You are trying to use the sample for a static source for a dynamic purpose.
Your source-property should not be a
url, but afunction:The correct samples are found here (source) and here (custom display).
Based on the comments, only alter your rendering to handle your products-response (see the second link).