I am trying to write a auto-complete with ajax in MVC5 but no matter what I try I get the error invalid JSON primitive. When I enter the url manually localhost:5088/GetData?inpt=[query] I am able to see the return json.
From what I understand online , I am giving the "data:" parameter wrong. I tried putting them in "" but it didn't work.
My Controller :
public JsonResult GetData(string inpt)
{
try
{
var node = //some values here , cause its too long I deleted it
foreach (var node in q)
{
string scity = node.Attribute("CityName").Value.ToUpper(new CultureInfo("tr-TR", false));
string ccity = node.Attribute("CityCode").Value;
string ccode = node.Attribute("CountryCode").Value;
if (ccity != oldcity)
{
result.Add(new HavaAlani { SehirAdi = scity, HavaAlaniKodu = ccity, HavaAlaniAdi = scity + ", " + ccode, Sehirmi = true });
oldcity = ccity;
}
result.Add(new HavaAlani { SehirAdi = scity, HavaAlaniKodu = node.Attribute("Code").Value, HavaAlaniAdi = node.Value, Sehirmi = false });
}
}
catch
{
}
return Json(result, JsonRequestBehavior.AllowGet);
}
}
My JS :
$('input.suggestBox').each(function () {
//$(this).jsonSuggest(air.Lines);
$(this).autocomplete({
source: function (request, response) {
$.ajax({
url: "dataAl/GetData",
data: { inpt: request.term },
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
return {
code: item.HavaAlaniKodu,
value: item.HavaAlaniAdi,
iscity: item.Sehirmi
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.responseText);
}
});
},
minLength: 2
}).data("ui-autocomplete")._renderItem = function (ul, item) {
var cls = "airport";
if (item.iscity)
cls = "city";
return $("<li></li>")
.data("item.autocomplete", item)
.append("<span class='span-" + cls + "'></span>")
.append("<a class='ui-autocomplete-" + cls + "'>" + item.value + " (" + item.code + ")" + "</a>")
.appendTo(ul);
};
});
Comment was getting a bit long so adding this as an answer-
The first thing to try would be modifying your content type per this post: MVC JSON method returning invalid JSON to JQuery?
Try "application/json".
also wrap your data object in
JSON.stringify()
If that doesn't work can you tell me where result is coming from in your action - I'm not seeing the declaration. Also add a break point and ensure that you can step into that method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With