ensnare
ensnare

Reputation: 42043

Unable to change global variable from local function

I'm trying to have a jQuery.getJSON() call change a global variable with the JSON array it returns:

var photo_info ;

//Advance to the next image
    function changeImage(direction) {

            jQuery('img#preview_image').fadeOut('fast');
            jQuery('#photo_main').css('width','740px');

            if (direction == 'next') {
                    jQuery.getJSON('/ajaxupdate?view&sort='+sort+'&a='+a+'&s=' + title_url_next, function(data) {
                            photo_info = data;
                            title_url = photo_info.title_url;                                                                                          
                            title_url_next = photo_info.preview_title_url_next;                                                                        
                            title_url_previous = photo_info.preview_title_url_previous;                                                                
                    });
            } else if (direction == 'prev') {
                    jQuery.getJSON('/ajaxupdate?view&sort='+sort+'&a='+a+'&s=' + title_url_previous, function(data) {
                            photo_info = data;
                            title_url = photo_info.title_url;
                            title_url_next = photo_info.preview_title_url_next;
                            title_url_previous = photo_info.preview_title_url_previous;
                    });
            }
}

However, the variable photo_info is only accessible from within the getJSON() function and returns undefined from anywhere else in the script.

What am I doing wrong?

Upvotes: 0

Views: 1313

Answers (3)

pedro
pedro

Reputation: 411

as Randal said Ajax call is asynchronous. Use the ajaxComplete function or replace the getJSON function with an .ajax call and use the photo_info var whithin the success function e.g.:

$.ajax({
  url: 'ajax/test.html',
  success: function(data) {
    $('.result').html(photo_info);
  }
});

Upvotes: 1

Joel Etherton
Joel Etherton

Reputation: 37533

JavaScript scoping isn't quite like standard scoping. It looks like you're actually losing your scope because of nested functions. Try giving this article a read:

http://www.robertsosinski.com/2009/04/28/binding-scope-in-javascript/

Upvotes: 1

Randal Schwartz
Randal Schwartz

Reputation: 44081

If you're looking at photoinfo in the rest of the script right after changeImage has returned, then of course it won't have a value, because the Ajax call is asynchronous. You need to rethink your application to be more event driven.

Upvotes: 1

Related Questions