Las llamadas ajax asíncronas estropean la fuente de la imagen

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;

preguntado el 04 de septiembre de 13 a las 02:09

2 Respuestas

Ajax is asynchronous, the call back gets called when the request is done, try this instead :

function ajax(path, profile) {
  $.ajax({
    type: "GET",
    url: "ajax.php",
    data: {'path': path},
    success: function(data) {
        profile.append($('<img/>', {src: data, 'class': 'thumb'));
    }
  })
}

//d3
ajax(d.id, profile);

Respondido el 04 de Septiembre de 13 a las 02:09

Usted obtiene <imge src="undefined" porque ajax does not return anything. Change you code to:

function ajax(path, callback) {
  $.ajax({
    type: "GET",
    url: "ajax.php",
    data: {'path': path},
    success: function(data) {
        callback(data);
    }
  })
}

y

var img = profile.append("img").attr("class", "thumb");
ajax(d.id, function(data) { img.attr("src", data); });

Respondido el 04 de Septiembre de 13 a las 02:09

I see where you're getting at. The problem is that d.id is not available outside the D3 callback function. - user1781186

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.