Henry Winn Henry Winn - 2 months ago 20
Ajax Question

Getting Data After jQuery getJSON

I'm trying to get photos through the facebook Graph API. Here's my code:

function getImgURL(photos, m) {
n=0;
while (typeof photos[n] !== 'undefined') {
photourl[m] = photos[n].images[2].source;
n++;
m++;
}
}

$('document').ready(function() {
var url = "https://graph.facebook.com/179877662120200";
var json = $.ajax(url);
console.log(json);
console.log(json.responseText);
var photos = $.parseJSON(json);
console.log(photos);
console.log(photos);
var m = 0;
getImgURL(photos, m);
while (typeof photos.paging !== 'undefined') {
json = $.ajax(photos.paging.next);
photos = $.parseJSON(json);
getImgURL (photos, m);
}
});


So looking at the log, it returns the variable json as an object. One property of the object is "responseText" but when I try to print that to the console it returns "undefined"

Answer

AJAX/JSON-P requests are (usually - always in the case of JSON-P) asynchronous operations - you need to receive and handle the response in a callback, not straight after the request.

The object you think you're getting is actually a deferred object generated by jQuery, not the response.

So:

$.getJSON(url).done(function(response) {
    console.log(response); //here's your response
});

Or, if you'd rather declare the callback later on for any reason:

var req = $.getJSON(url);
//other, synchronous code here
req.done(function(response) { console.log(response); });

Some other points:

1) jQuery automatically parses JSON strings returned as part of JSON-P requests, so you don't need to parse it yourself as you currently are

2) your n var is (seemingly) global

3) you might want to improve your indentation as the code isn't super readable

4) your loop can be simplified to while(photos[n]) {...