I am using the following script to get all the tags from my controller and use it as typeahead
<script>
$(function () {
var substringMatcher = function (strs) {
return function findMatches(q, cb) {
var matches, substringRegex;
matches = [];
substrRegex = new RegExp(q, 'i');
$.each(strs, function (i, str) {
if (substrRegex.test(str)) {
matches.push({ value: str });
}
});
cb(matches);
};
};
var states = (function () {
var states = null;
$.ajax({
'async': false,
'global': false,
'url': "../my/GetAllTags",
'dataType': "json",
'success': function (data) {
states = data;
}
});
return states;
})();
var tags = $('input.stateinput');
tags.tagsinput();
$(tags).each(function (i, o) {
var taginput = $(o).tagsinput('input');
taginput.typeahead({
hint: true,
highlight: true,
minLength: 1,
autoselect: true
}, {
name: 'states',
displayKey: 'val',
source: substringMatcher(states)
}).bind('typeahead:selected', $.proxy(function (obj, datum) {
$(o).tagsinput('add', datum.value);
taginput.typeahead('val', '');
}));
$(taginput).blur(function () {
taginput.typeahead('val', '');
});
});
});
</script>
when I load the site I get an error in the console for my controller and When I press any key I get this error for a null value (which is obvious as I cannot access the GetAllTags)
Where My controller is the following
[HttpPost]
public JsonResult GetAllTags()
{
List<Models.Tags.MTag> Tag_List = new List<Models.Tags.MTag>();
Tag_List = GenerateList.GetTags();
var TAGS = Tag_List;
return Json(TAGS.Select(t => new { id = t.Tag_id, val = t.Tag_name }),
JsonRequestBehavior.AllowGet);
}
what am I doing wrong?
Cheers
FYI: If I directly add data, it works just fine - such as
var states = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California',
'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii',
'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky',
'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan',
'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska',
'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York',
'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon',
'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota',
'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington',
'West Virginia', 'Wisconsin', 'Wyoming'
];
The error you are seeing in the Javascript console on chrome is because you are trying to call a POST with a get request so it is not finding the API. Try this:
$.ajax({
type: 'POST'
'async': false,
'global': false,
'url': "../my/GetAllTags",
'dataType': "json",
'success': function (data) {
states = data;
}
});