Async ajax calls messes up image source
I'm using D3.js in conjunction with the Facebook PHP SDK to display the
visitors friends. Each friend is displayed in a small div with name and
profile picture.
My problem is that the Facebook API doesn't return a direct link to the
profile picture. Instead, you have to use a URL like
https://graph.facebook.com/UserID/picture?redirect=false, and the URL to
the picture is returned in JSON. All other friend data is already fetched
and stored in a Javascript array.
Now, I set up an AJAX call to deal with this, but it doesn't work because
of its asynchronous nature. Once the picture URLs are fetched, the DOM is
already loaded and the images get <img src="undefined">.
From main.js
function ajax(path) {
$.ajax({
type: "GET",
url: "ajax.php",
data: {'path': path},
success: function(data) {
return data; //returned data is correct
}
})
}
// d3 code
profile.append("img")
.attr("src", function(d) { return ajax(d.id); }) //this is "undefined"
.attr("class", "thumb");
From ajax.php
$path = file_get_contents('https://graph.facebook.com/' . $_GET['path'] .
'/picture?redirect=false');
echo json_decode($path)->data->url;
No comments:
Post a Comment