0

Here is my code:

var name;
function getFBName(username) {
    $.getJSON('http://graph.facebook.com/' + username, function (d) {
        name = d.name;
    });
}
getFBName("zuck");
console.log(name);

I am struggling since hours but I can't get the getFBName function to return the name of the user.

This is the JSON btw:

{
   "id": "4",
   "first_name": "Mark",
   "gender": "male",
   "last_name": "Zuckerberg",
   "link": "https://www.facebook.com/zuck",
   "locale": "en_US",
   "name": "Mark Zuckerberg",
   "username": "zuck"
}
Elmo
  • 6,409
  • 16
  • 72
  • 140
  • AJAX calls are not synchronous(Asynchronous Javascript and XML) . Function call are. The return value will come back from the AJAX after the function has finished. – jwatts1980 Apr 17 '14 at 20:46
  • Please try to access http://graph.facebook.com/zuck from your browser, and let us know the result. it will be better if you capture the response with fiddler. – DadyFuji Apr 17 '14 at 20:59

1 Answers1

4

As @jwatts1980 said, this is a matter of order of execution. $.getJSON will return immediately, before the response has arrived to the client, so when you run console.log, it will still be waiting. One possible solution is:

function getFBName(username) {
    $.getJSON('http://graph.facebook.com/' + username, function (d) {
        console.log(d.name);
    });
}
getFBName("zuck");

Which will log Mark Zuckerberg correctly. If you have multiple ways of handling the output, it may also be interesting to set a callback function:

function getFBName(username, callback) {
    $.getJSON('http://graph.facebook.com/' + username, function (d) {
        callback(d.name);
    });
}

function handleName(name) {
    // Do a lot of things here
    console.log(name);
}

getFBName("zuck", handleName);
augustomen
  • 8,977
  • 3
  • 43
  • 63