views:

172

answers:

3

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? Thanks for your help.

+1  A: 

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.

Randal Schwartz
Hi -- photo_info is not accessible even from within the changeImage() function. Thanks.
ensnare
Randal is right, because even within the changeImage function the ajax call has not returned yet. See my answer for options on how to solve the problem.
pedro
+1  A: 

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/

Joel Etherton
+1  A: 

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);
  }
});
pedro