0

I have this code it works perfectly:

$.getJSON('/admin/get_acronyms', function(data) {
    //load JSON
    $.each(data, function(key, val) {
        if(key === 'error') {
            alert(val);
        } else {
            //Update typeahead source
            autocomplete.data('typeahead').source = val;
        }
    });
});

And I want to minimize it inside this function for code reusing:

var getAndAppendJSON = function(url) {
    var result;
    $.getJSON(url, function(data) {
        $.each(data, function(key, val) {
            return val;
        });
    });
};


var arr = getAndAppendJSON('/admin/get_acronyms');
autocomplete.data('typeahead').source = arr;

But this function doesn't work :(.

JS Console shows me that var arr is undefinied

Anyone knows why? Thanks in advance.

Carlos Azaustre
  • 395
  • 2
  • 6
  • 15
  • 1
    possible duplicate of [How to return the response from an AJAX call from a function?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call-from-a-function) – Felix Kling Mar 19 '13 at 23:31

2 Answers2

4

getAndAppendJSON doesn't actually return anything. It initiates an AJAX call that completes after its invocation has completed. What you should do is use the returned data inside the callback:

var getAndAppendJSON = function(url) {
    var result;
    $.getJSON(url, function(data) {
        autocomplete.data('typeahead').source = data;
    });
};

Your request will take a bit of time to make a trip to the server and back. This is what handlers are for, to be able to work with data once it is returned to you after an indeterminate period of time.

Asad Saeeduddin
  • 46,193
  • 6
  • 90
  • 139
3

Because AJAX is "asynchronous". You have your AJAX success handler return val, but where are you returning to?

When you execute

var arr = getAndAppendJSON('/admin/get_acronyms');

the AJAX call is getting sent to the server, but there is nothing being returned from that function. Therefore arr is undefined. By the time the AJAX call comes back from the server, the rest of the JS has long moved on.

To do what you are trying to achieve, the assignment has to happen in the callback function:

var getAndAppendJSON = function(url) {
    var result;
    $.getJSON(url, function(data) {
        autocomplete.data('typeahead').source = data;
    });
};
Steve
  • 8,609
  • 6
  • 40
  • 54