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.
The function returns long before the ajax request is even made. Use
datain the callback function (You are actually logging it in the callback function, where it’s guaranteed to be available ). The$.getJSONdoesn’t take callback function just for fun, but exactly for this reason.You can do this though:
Instead of trying to do:
Which will not work unless you set the request to synchronous, which has worse problems.