I need help for my javascript, I'm trying to create a search form with autocompletion with typeahead, but for the moment I'm getting "undefined" when I write something in the input : Undefined
This is my code :
$(document).ready(function () {
var term = $("#tags").val();
var datas = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.whitespace,
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: "{{ path('autocomplete') }}/%QUERY%",
wildcard: "%QUERY%",
filter: function (datas) {
return $.map(datas, function (data) {
return $.map(data, function (item) {
console.log(item);
return {
item_id: item.id,
item_name: item.name,
item_image: item.image,
};
})
});
},
},
});
datas.initialize();
$("#tags").typeahead(
{ hint: true, },
{
name: "datas",
source: datas.ttAdapter(),
templates: {
suggestion: function (item) {
return `<div class='datafetch'><ul><li>${item.name}</li></ul></div>`;
},
},
}
);
});
And you can see my controller here : Controller
The console log when I write something in the input : console.log
Thanks for your help !! :)
CodePudding user response:
As seen in the screen of your console.log neither the property item.id
nor item.name
is defined, only item.title
and item.image
is defined.
thats why you get the undefined error.
CodePudding user response:
I changed my code to :
$(document).ready(function () {
var term = $("#tags").val();
var datas = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.whitespace,
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: "{{ path('autocomplete') }}/%QUERY%",
wildcard: "%QUERY%",
filter: function (datas) {
return $.map(datas, function (data) {
return $.map(data, function (item) {
console.log(item);
return item;
})
});
},
},
});
datas.initialize();
$("#tags").typeahead(
{ hint: true, },
{
name: "datas",
source: datas.ttAdapter(),
templates: {
suggestion: function (item) {
return `<div class='datafetch'><ul><li>${item.title}</li></ul></div>`;
},
},
}
);
});
And now it's working ! :D