tekknolagi
tekknolagi

Reputation: 11022

javascript variable is undefined

I'm writing a small Flickr image grabber app, and we have a JSON proxy on our own servers. The function below grabs the images from a photoset given the id.

function getPhotosFromPhotoset(p_id) {
    var data;
    $.getJSON('/flickr_get_photos', {
        photoset_id: p_id
    }, function(res) {
        data = res;
        console.log("res: " + JSON.stringify(data));
        if (res.status == 'ok') {
            if (res.data.length > 0) {
                //nada                                                                                                                            
            } else {
                data.status = "error: Photoset has no photos.";
            }
        } else {
            data.status = "An unknown error occurred; please try again.";
        }
    });
    return data; //undefined?!
}

Why is does data suddenly become undefined? When I console.log it inside of the getJSON, it's perfectly valid.

Upvotes: 0

Views: 265

Answers (3)

Esailija
Esailija

Reputation: 140236

The function returns long before the ajax request is even made. Use data in the callback function (You are actually logging it in the callback function, where it's guaranteed to be available ). The $.getJSON doesn't take callback function just for fun, but exactly for this reason.

You can do this though:

function getPhotosFromPhotoset(p_id) {
    return $.getJSON('/flickr_get_photos', {
        photoset_id: p_id
    });
}

getPhotosFromPhotoset(1).then(function(data) {
    //Use data here
});

Instead of trying to do:

var data = getPhotosFromPhotoset(1); //will not work

Which will not work unless you set the request to synchronous, which has worse problems.

Upvotes: 4

Justin Ethier
Justin Ethier

Reputation: 134255

AJAX executes asynchronously, so when you say:

return data; //undefined?!

That code is executing before the code in function (res), which is why data is undefined. If you want to do something with the data, you need to pass a callback function to getPhotosFromPhotoset which will be executed by the success callback of getJSON.

Does that make sense?

Upvotes: 1

JaredMcAteer
JaredMcAteer

Reputation: 22545

It doesn't suddenly become undefined. getJson is an asynchronous call, the function that sets the data value is what gets call when the server returns a response, getPhotosFromPhotoset doesn't wait for the server to respond before completing execution and thus the data value has not been set with anything yet.

Upvotes: 2

Related Questions