daveredfern
daveredfern

Reputation: 1255

accessing variables outside ajax

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.

Upvotes: 3

Views: 18105

Answers (5)

gizmo
gizmo

Reputation: 41

Here is another option. You create a function that return an ajax call like this.

 function flickrImages (){
 return $.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"
});
}

Then on your code somewhere, you call this function an retrieve the success or in my case the .done() function like this

var result= flickrImages ();
   flickrImages = [];
   result.done(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 + '">';
    });
 });
console.log (flickrImages);

Upvotes: 1

Cody
Cody

Reputation: 101

As said by Karl Agius a "The ajax call is asynchronous". For this you just have to add

async: false,

to your ajax request. Here is you code looks after adding this:

$.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",
    async: false,
    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 + '">';
        });
    }
});

But its not a good practice to stop asynchronous in ajax call. But will work for you. Use Ajax callback on success instead (check here).

Upvotes: 1

Karl Agius
Karl Agius

Reputation: 61

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?

Upvotes: 3

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114417

Define a global variable outside of your ajax call and assign it a value

var myData

$.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) {
        myData = data
        myFunction()
    }
});

Upvotes: 1

wsanville
wsanville

Reputation: 37516

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.

Upvotes: 9

Related Questions