I am trying to make the typeahead remote source to a web method which will be repsond with results in JSON format.
Ajax is getting success and it;s returing the results properly . The console in the below code will print like below
[{"Id":"1","Value":"Midhun"},{"Id":"2","Value":"Midhun2"}]
But the typeahead suggestions are all undefined
var typeHeadEngine = new Bloodhound({ name: 'Name', remote: { url: 'page.aspx/method',
ajax: { type: "POST", data: JSON.stringify({ "query": '%QUERY' }), contentType: "application/json; charset=utf-8", dataType: "text", success: function (data) { var obj = JSON.parse(data); console.log(obj.d); return obj.d; } } }, datumTokenizer: function (d) { return Bloodhound.tokenizers.whitespace(d.val); }, queryTokenizer: Bloodhound.tokenizers.whitespace }); typeHeadEngine .initialize(); $('.typeahead').typeahead({ hint: true, highlight: true,
minLength: 3 }, { name: 'Name', displayKey: 'Value', source: typeHeadEngine.ttAdapter()
});
Web method is returing JSON string which am converting to array in the ajax success function. During googling i found that typeahead requires array and not JSON object ,so I am converting into array.
i went through plently of similar questions to figure it out. But i am unable to do so ,
Can anyone please help to figure out what i am doing wrong here ?
You should not use the success
field of the ajax options to transform your JSON,
instead you have to use the filter
field provided by Bloodhound:
var typeHeadEngine = new Bloodhound({
name: 'Name',
remote: {
url: 'page.aspx/method',
ajax: {
type: "POST",
data: JSON.stringify({
"query": '%QUERY'
}),
contentType: "application/json; charset=utf-8",
dataType: "text"
},
filter: function (data) {
var obj = JSON.parse(data);
console.log(obj.d);
return obj.d;
}
},
datumTokenizer: function (d) {
return Bloodhound.tokenizers.whitespace(d.val);
},
queryTokenizer: Bloodhound.tokenizers.whitespace
});