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.

1

2 Answers 2

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.

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

3 Comments

Thank you so much @Asad! Now I know how use better the function :)
@CarlosAzaustre You're welcome. Please do take a look at the question mentioned by Felix Kling, which has a great explanation of the asynchronicity in AJAX.
Anyway, What If I want to change "autocomplete.data('typeahead').source = data;" for other to automatize? Thanks in advance
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;
    });
};

Comments

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.