I'm still new to JS: and I'm having trouble connecting two ajax requests. The first is simple:
ask fb for a user id:
FB.api('/me', function(user) {
if (user) {
}
});
Post a custom facebook action on a custom fb object:
function myfunction()
{
FB.api(
'/me/fb:myaction',
'post',
{ myobject: '/object/<%=@obj.id%>' },
function(response) {
if (!response || response.error) {
console.log('Error occured');
} else {
console.log('FB POST was successful! Action ID: ' + response.id);
$.ajax({
type: "POST",
url: "/record_action",
data: { facebook_id: "John", item_id: "<%= @candidate.id %>" },
dataType: 'json',
success: function(data) {
console.log(data);
}
}).done(function( msg ) {
console.log(msg);
});
}
});
}
How can I save the user.facebook_id and pass it to a call of myfunction(). When I try something like:
FB.api('/me', function(user) {
if (user) {
myvar = user.facebook_id
}
});
and try passing myvar to the myfunction call it does not work. I'm sure this is uber trivial. How can this be done?
The better answer is to use a closure (probably the first query's success function) to capture this answer, and do the rest of the work inside that closure.
The less effective (but perhaps more pragmatic while you're learning) is to put the data in a global variable between the two calls. There are a myriad of problems with global variables in JavaScript though and they should be avoided like the plague if you're ever going to not fully control all scripts running on the page.