views:

28

answers:

2

I am developing a facebook app and I seem to have got stuck on an issue.

I am trying to assign the username to a variable by calling the below code, but the variable is returning null.

var current_user ='';
var arUser = FB.Connect.get_loggedInUser();
FB.Facebook.apiClient.users_getInfo(arUser, ["name"], 
  function (user, exec) 
  { //alert(user[0].name); - this works!!
  current_user = user[0].name; 
});

alert(current_user); // this returns null :(

I get a value if I do an alert(user[0].name) within the function. I get a feeling that I need to wait for the response from execution of users_getInfo() before using the current_user variable, but not sure how..

Help much appreciated.

A: 

you should process the data in the callback function, due to this call is asynchronous.

zerkms
isnt that what function(user, exec) is? the last parameter of the FB api calls are usually the (aync/sync) callback function.
RPM1984
@RPM1984: yes it is. but he is trying to work with data **outside** that callback, which is wrong.
zerkms
lol, i didnt even see that last line - alert(current_user). i was looking at current_user = user[0].name - which should work. my bad =)
RPM1984
A: 

Your alert is being called before the AJAX call returns. Just wrap code that uses the current_user variable in a separate function, and invoke that function only from the users_getInfo success handler.

Another option would be to have a timer that polls for the variable, but I see no reason to do such a thing.

Gintautas Miliauskas

related questions