views:

948

answers:

2

Hey guys,

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!

+5  A: 

It's because $.getJSON is asyncrhonous. As soon as you send the request, your function getAutocompleteData() continues executing, returning effectively 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);
});
Seb
thanks much man, forgot about that
Jimmy
A: 

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

Cheers, Sean

seanxe
that wont change anything
jmein