2

I'm trying to use the jquery ui autocomplete feature with an ajax datasource and I just can't see what is wrong with my code.

Here is my code

$(document).ready(function () {

        var data = new Portalen.LitteraNumberData();

        $("#LitteraNumber").autocomplete({
            minLength: 1,
            source : function (request, response) {
                var customerId = $("#CustomerId").val();
                return response(data.loadLitteraNumbers(customerId));
            }
        });
    });

and in a js file I have this:

Portalen.LitteraNumberData = function () { };

Portalen.LitteraNumberData.prototype = function() {

var loadLitteraNumbers = function(customerId) {
    $.get("/Orders/GetLitteraNumbers", { customerId: customerId }, function (response) {
        return response;
    });
};

return {
    loadLitteraNumbers: loadLitteraNumbers
};
}(); 

The ajax call is working, I get the correct response but the autocomplete feature just wont happen. Is LitteraNumberData returning the wrong thing? All suggestions are appreciated.

1 Answer 1

3

Try this:

$(document).ready(function () {
    var data = new Portalen.LitteraNumberData();
    $("#LitteraNumber").autocomplete({
        minLength: 1,
        source : function (request, response) {
            $.get("/Orders/GetLitteraNumbers", { customerId: request.term }, function (data) {
                response(data);
            });
        }
    });
});

I've replaced $("#CustomerId").val() by request.term. Moreover, the function does not need to return the response.

The $.get function is asynchronous so you cannot put it elsewhere.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your answer, I was really hoping to be able to encapsulate the scripts in js files and make them some what reusable in other places. I would really like to know why my approach isn't working.
Your approach isn't working because $.get is asynchronous. loadLitteraNumbers() finishes before $.get returns a result. I think this is the point.
What a version autocomplete with jquery ui? Uncaught ReferenceError: Portalen is not defined

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.