accessing variables outside ajax

14,027

Solution 1

The reason why flickrImages is undefined where your comment is, is because the call to $.ajax is asynchronous, which means it does not block until your request completes.

That's why there is a success function that gets "called back" when the underlying HTTP request completes. So, you need to handle your flickrImages variable from your success function, or alternatively, from your success function, pass flickrImages to some other function which does your processing.

Solution 2

The ajax call is asynchronous, so it won't wait around for an answer - it will just go ahead and run the rest of the script. Passing async:false in the settings (see http://api.jquery.com/jQuery.ajax/) should solve your problem, though it will make it a lot slower as the script will have to wait for the ajax call to return.

It would be neater for the rest of the script to be called from the success callback as you tried to do - how is it that xmlTitle and xmlExcerpt are unavailable there?

Share:
14,027
daveredfern
Author by

daveredfern

Updated on June 25, 2022

Comments

  • daveredfern
    daveredfern almost 2 years

    I have the following code:

    var src, flickrImages = [];
    
    $.ajax({
        type: "GET",
        url: "http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=bf771e95f2c259056de5c6364c0dbb62&text=" + xmlTitle.replace(' ', '%20') + "&safe_search=1&per_page=5&format=json",
        dataType: "json",
        statusCode: {
            404: function() {
                        alert('page not found');
                    }
        },
        success: function(data) {
            $.each(data.photos.photo, function(i,item){
                src = "http://farm"+ item.farm +".static.flickr.com/" + item.server + "/" + item.id + "_" + item.secret + "_s.jpg";
                flickrImages[i] = '<img src="' + src + '">';
            });
        }
    });
    
    // undefined returned here for flickrImages
    
    map.setZoom(13);
    map.setCenter(new google.maps.LatLng(xmlLat,xmlLng));
    infowindow.setContent('<strong>' + xmlTitle + '</strong><br>' + xmlExcerpt + '<br><br>' + flickrImages.join(''));
    infowindow.open(map,this);
    

    I am trying to access flickrImages variable outside the ajax so I am able to put it inside a infowindow for google maps. Unfortunately outside the ajax it returns undefined.

    I tried moving the flickr things into the ajax but unfortunately it then loses some of the other information such as xmlTitle and xmlExcerpt.

    Any help is much appreciated.

    Thanks in advance,

    Dave.