0

I'm having issues with scope in Javascript. Take a look at this code, for example:

$(function() {
    var items = "GLOBAL";

    $('.add').click(function() {            
        $.post("main/get", { 'get' : 'all' },
        function(data){
            items = String(data.result);
            items = items.split(' *** ');
            alert(items);
        }, "json");
        alert(items);
        return false;
    });

    $(".add").autocomplete({
        source: items
    });
});

I'm trying to get autocomplete working, and it almost is. The only problem is that I can't seem to change items outside of the inner-most function. The first alert gives me what I'm looking for, but the second just gives me "GLOBAL." The bottom autocomplete part has to be able to access it.

Any help is appreciated!

Thanks!

1
  • can you please give a link to a working demo for a better understanding of the problem? Commented Mar 22, 2011 at 2:16

1 Answer 1

2

It is not just a scope issue. Since your request is very likely to happen asynchronously (unless configured otherwise) it won't work that way anyway. You have to initialize the autocomplete in the callback function which gets called once your AJAX request is complete:

$(function() {
    $('.add').click(function() {            
        $.post("main/get", { 'get' : 'all' },
        function(data){
            var items = String(data.result);
            items = items.split(' *** ');
            $(".add").autocomplete({
                source: items
            });
        }, "json");
    });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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