Question

I am using jQuery's auto-complete plugin for a simple search form. I am having trouble converting my JSON object data into an array for usage with auto-complete.

My code:

var listOfOrderedByNames = getAutocompleteData();
$('#OrderedBy').autocomplete(listOfOrderedByNames);

function getAutocompleteData() {
    var output;
    $.getJSON('AJAX/GetOrderedByNames', function(data) {
        $.each(data, function(index, optionData) {
            output += optionData + "|";
        });
    });
    return output;
}

My JSON data that is returned looks like this:

    ["Jimmy","John", "Etc",null]

For some reason it looks like what I'm getting back from that getAutocompleteData function is an empty string and I don't know what is wrong.

Please help!

Was it helpful?

Solution

It's because $.getJSON is asynchronous. As soon as you send the request, your function getAutocompleteData() continues executing, returning nothing.

You should enclose everything in the callback function you're passing to the getJSON method:

var output;
$.getJSON('AJAX/GetOrderedByNames', function(data) {
    var output = "";
    $.each(data, function(index, optionData) {
        output += optionData + "|";
    });
    $('#OrderedBy').autocomplete(output);
});

OTHER TIPS

Try changing the var ouput; line to var output = '';

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top