user2804030 user2804030 - 9 days ago 6
Ajax Question

jquery autocomplete with ajax not working

Here's my code:

<script type="text/javascript">
$(document).ready(function () {
$(".list tr:even").addClass("even");
var cityList = [];
$("#autocomplete").autocomplete({
source: function () {
$.ajax({
type: "POST",
url: "flight/fillcitydropdownlist",
data: "{'cityname':'" + $('#autocomplete').val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.cities.length > 0) {
for (var i = 0; i < data.cities.length; i++) {
cityList.push(data.cities[i].Main);
}
}
return cityList;
}
})
}
})
});




I don't see why this is not working. The ul element is added at the bottom of the page, but no li s are added to it. although the cityList is filled. Is the problem related to how I am passing an array to autocompelet source?

Answer

You cannot return a value from the source function, it receives a callback function as the second argument, once the response is back you need to pass the response data to the callback function

$(document).ready(function () {
    $(".list tr:even").addClass("even");
    var cityList = [];
    $("#autocomplete").autocomplete({
        source: function (request, callback) {
            $.ajax({
                type: "POST",
                url: "flight/fillcitydropdownlist",
                data: "{'cityname':'" + request.term + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    callback($.map(data.cities, function(obj){
                        return obj.Main
                    }))
                }
            })
        }
    })
});