Daniel Newtown Daniel Newtown - 6 months ago 15
jQuery Question

jQuery Autocomplete does not work with back-end generated JSON

I am using jQuery autocomplete as following, if I use default url of the jQuery the code works but when I use my back-end generated JSON and type something in my input element, I am sure that the function calls the back-end and the back-end generates the JSON but the autocomplete does not show the values of the returned JSON.

$(function() {
$("#name").autocomplete(
{
source : function(request, response) {
$.ajax({
url : "http://localhost:2051/myproject/names",
dataType : "jsonp",
data : {
q : request.term
},
success : function(data) {
response(data);
}
});
},
minLength : 2,

});
});


The JSON that back-end in address

"http://localhost:2051/myproject/names"


returns is as following

["Podgorica, CG, Yugoslavia"]


When I type pod with the url that comes with default version of the autocomplete, it shows and the suggestion box successfully get populated.

["Podgorica, CG, Yugoslavia"]


I am not sure why it does not show the returned JSON of the back-end. Another question is how to have a map of the items, so rather than value of the item I pass its key to the back-end?

Answer

this code working find.

   $("#tags").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: "http://localhost:43580/bmac/home/index",
                    dataType: "json",
                    data: { q: request.term },
                    success: function (data) {
                        response(data);
                    }
                });
            }
        });

and backend

[AllowAnonymous]
    public virtual ActionResult Index()
    {
        return Json(new[] { "Podgorica CG Yugoslavia" }, JsonRequestBehavior.AllowGet);
    }

return

["Podgorica CG Yugoslavia"]