Unable to pass a response form facebook to another function - javascript

If you view this question thank you in advance!, I am working on pulling data from Facebook.
I am trying to pull the username from Facebook so i can use it in a later stage I have embedded the following code in the FB Root div.
I know the retrieve works! however i am not able to pass it on to the function returndata I am relative new to javascript could you please help me out? i have tried everything
There is an alert in there to check if it is retrieving data
<div id="fb-root"></div>
<script type="text/javascript">
$(document).ready(function()
{
var appId = "121070974711874";
// If logging in as a Facebook canvas application use this URL.
var redirectUrl = "http://apps.facebook.com/bggressive";
// If logging in as a website do this. Be sure to add the host to your application's App Domain list.
var redirectUrl = window.location.href;
// If the user did not grant the app authorization go ahead and tell them that. Stop code execution.
if (0 <= window.location.href.indexOf ("error_reason"))
{
$(document.body).append ("<p>Authorization denied!</p>");
return;
}
// When the Facebook SDK script has finished loading init the
// SDK and then get the login status of the user. The status is
// reported in the handler.
window.fbAsyncInit = function()
{
FB.init({
appId : appId,
status : true,
cookie : true,
oauth : true
});
FB.getLoginStatus (onCheckLoginStatus);
};
(function(d)
{
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
function onCheckLoginStatus (response)
{
if (response.status != "connected")
{
top.location.href = "https://www.facebook.com/dialog/oauth?client_id=" + appId + "&redirect_uri=" + encodeURIComponent (redirectUrl) + "&scope=user_photos,friends_photos";
}
else
{
FB.api('/me', function(response)
{
PASON = response.username
alert(response.username)
});
}
}
});
function returndata()
{
get = PASON
return get
};
</script>

I think you are calling the function returndata() at any random point which you can't do. The reason is- the variable PASON is assigned value asynchronously. So, you have to code in such a way that you call returndata() after the value is assigned!
Its not quite clear what you are trying to do with the function returndata(). But, I hope your concept is clear now.

Related

Facebook Tab / Page Authentication issues: getLoginStatus always returns not_authorized

I have the following code for my Facebook Application:
window.fbAsyncInit = function() {
FB.init({
appId : 'XXXXXX', // App ID
channelUrl : '/channel.html', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// Additional initialization code here
//***************************************************
//* FanGate for Facebook
//***************************************************
var hideLogin = function(){
$("#login-fb").hide();
}
var showLogin = function(){
$("#login-fb").show();
}
var doLogin = function(){
FB.login(function(response) {
if (response.session) {
hideLogin();
checkLike(response.session.uid)
} else {
// user is not logged in
}
});
}
var checkLike = function(user_id){
var page_id = "XXXXXXXXX"; //coca cola
var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+"and uid="+user_id;
var the_query = FB.Data.query(fql_query);
the_query.wait(function(rows) {
if (rows.length == 1 && rows[0].uid == user_id) {
$("#thirsty_thursdays").show();
} else {
$("#fan_gate").show();
}
});
}
FB.getLoginStatus(function(response) {
console.log(response.status);
if (response.status == 'connected') {
hideLogin();
checkLike(response.authResponse.userID)
} else {
showLogin();
}
}, true);
$("#login-fb a").click(doLogin);
};
// Load the SDK Asynchronously
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
response.status always returns not_authorized and I am really unclear why. I am logged into Facebook and the application is a simple Page Tab. I have recently added App on Facebook to the setting to see if that helps but no luck.
I have not seen any additional info on the Facebook JS SDK docs that give any info.
I am basically looking to show content if the user is logged in and is a fan of a certain page and hide the content if not. (commonly called fan gate)
Would have posted this as a comment but I cant yet...
After your tab loads and the FB.getLoginStatus() response indicates "not_authorized" (and therefore, I assume, shows your login button) -- what happens if you then click your login button? Is it giving the facebook pop-up prompt to authorize the app? (I'm hesitant to ask this but are you in fact sure that you've authorized the app?) Or does it just do nothing?
-In the callback for FB.login.. what does it output if you add a console.log(response.authResponse) ?
-I believe the channelUrl is supposed to be fully qualified whereas you have it root relative.. Not sure that would have any impact on your issue but might want to try it.. see https://developers.facebook.com/docs/javascript/gettingstarted/#channel

storing facebook javascript functions in a file and using them

Hi I am writing a code to login the user through the facebook. I store all the function in a file along with other javascript function. I try calling login function from another javascript function and get following error: login is not defined. Here is the code for index.html
<html xmlns:fb="http://ogp.me/ns/fb#">
<head>
<script type="text/javascript" src="javascript.js"></script>
</head>
<body>
<div id="fb-root"></div>
Hi!
</body>
</html>
Here is javascript.js
window.fbAsyncInit = function() {
// init the FB JS SDK
FB.init({
appId : '213443452146381', // App ID from the App Dashboard
channelUrl : '//http://abc.in/', // Channel File for x-domain communication
status : true, // check the login status upon init?
cookie : true, // set sessions cookies to allow your server to access the session?
xfbml : true // parse XFBML tags on this page?
});
FB.getLoginStatus(function(response) {
if (response.status === 'connected')
{
alert('connected');
}
else if (response.status === 'not_authorized') {
alert('not_authorized');
login();
} else {
alert('chillonly');
login();
}
});
function login() {
FB.login(function(response) {
if (response.authResponse) {
alert('connected');
testAPI();
} else {
alert('not_connected_login');
testAPI();
}
});
}
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
});
}
// Additional initialization code such as adding Event Listeners goes here
};
// Load the SDK's source Asynchronously
// Note that the debug version is being actively developed and might
// contain some type checks that are overly strict.
// Please report such bugs using the bugs tool.
(function(d, debug){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all" + (debug ? "/debug" : "") + ".js";
ref.parentNode.insertBefore(js, ref);
}(document, /*debug*/ false));
// ]]>
function sayhi()
{
alert('Hi');
login();
}
I doubt if the facebook jdk is getting loaded at all. Please suggest a way to achieve this.
The method login() is not accessible since it is in a local scope.
If you want function login() { to be used outside of that scope, you need to make it global or part of some global namespace.
Change
function login() {
to
window.login = function () {
First of all, move the functions out of the window.fbAsyncInit. They are not accessible since in the local scope.
Then, you can have a flag that will only set to true when the JS-SDK is loaded, and you can "block" any process outside the window.fbAsyncInit till the flag is set. Something like:
var isLoaded = false;
window.fbAsyncInit = function()
{
isLoaded = true;
...
...
}
function myFunc(myVar)
{
if(isLoaded)
{
// Do FB related stuff
}
}

Facebook user email id using javascript SDK

I am currently using the following code to get the email id of the user using my app
function get_id(cb){
FB.init({
appId : .......,
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
FB.login(function(response) {
if (response.authResponse) {
var token = response.authResponse.accessToken;
alert(token);
accessToken = token;
FB.api('/me?access_token=' + token + '', function (response) {
cb(response.email);
});
}
},{scope: 'email'});
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
}; // ending of get_id()
get_id(function (email) {
userID=email;
alert(email);
});
the current code is in a separate javascript file and this function is called when a button is pressed , I have also included <script src="http://connect.facebook.net/en_US/all.js"></script> in the HTML file . my browser (google chrome) gives me the following error each time I try and access it
"Uncaught ReferenceError: FB is not defined "
I am relatively new to developing Facebook apps , so all the reference I have is the developers page at facebook , I am sure it is a small error but I just cant wrap my head around it , appreciate it if anybody could point out where I could be going wrong
Your code will not load correctly. This part:
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
Should not be inside any function, put this in a script tag, after the body opening. It can't be in a separate file. This only does a async-load of all.js, that is the Facebook's JS SDK. If you are using the async-load, you should not put <script src="http://connect.facebook.net/en_US/all.js"></script> in your document, because this will do a sync-load.
This other part of your code:
FB.init({
appId : .......,
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
Also should not be inside the function. This fragment is responsible for starting the FB JS SDK in your page, with your app information, it only have to be called one time for each page, otherwise you will be starting the engine multiple times and it will have a caotic behavior. The "FB" object will only be created after the FB JS SDK loads. You don't know when it's going to happen, because of the async load. So you must assign the FB.init to this window event:
window.fbAsyncInit = function() {
FB.init({
appId : .......,
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
};
You want to create a get_id function that uses the Facebook information. You have to be careful with that. With you are sure that this function will be called after the complete load of FB JS SDK, you can create it in any part of your page. BUT I think the most safe way is to create it inside the window.fbAsyncInit. Don't worry about the token, the SDK does it for you:
window.fbAsyncInit = function() {
FB.init({
appId : .......,
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
function get_id(cb){
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me', function (response) {
cb(response.email);
});
}
},{scope: 'email'});
}
};
But when you do that, you will be not sure if your function was already created or not. So when you call it, you will have to test for it's existence:
if(get_id && typeof get_id == 'function') {
// It's safe to call your function, go ahead
get_id(function (email) {
userID=email;
alert(email);
});
} else {
// Your function does not exists yet, do other stuff
}
Good luck!
You need to put:
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
out of get_id function. So it was called before you press the button
PS: you don't need to pass ?access_token= manually - FB JS SDK does that for you

Can I access a user's friend status using Facebook Graph API?

I am making an web app that shows the authenticated user's friends statuses. Is there anyway I can do this using Facebook's graph API? The only thing I am finding is FQL which I can't use because I am not allowed to use php.
Edit: Also I don't need alot of statuses. I only need their friends latest one.
Edit: fbID is the facebook ID. Here is my code:
<script>
var self;
(function(d){ // Load the SDK Asynchronously
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
window.fbAsyncInit = function() { // Init the SDK upon load
FB.init({
appId : '190843834372497', // App ID
channelUrl : 'http://people.rit.edu/~cds7226/536/project3/channel.html', // Path to your Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// listen for and handle auth.statusChange events
FB.Event.subscribe('auth.statusChange', function(response) {
if (response.authResponse) { // user has auth'd your app and is logged into Facebook
FB.api('/me', function(me){
if (me.name) {
document.getElementById('auth-displayname').innerHTML = me.name;
//Add rest of code here ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
self=me;
}
})
document.getElementById('auth-loggedout').style.display = 'none';
document.getElementById('auth-loggedin').style.display = 'block';
} else { // user has not auth'd your app, or is not logged into Facebook
document.getElementById('auth-loggedout').style.display = 'block';
document.getElementById('auth-loggedin').style.display = 'none';
}
});
document.getElementById('auth-loginlink').addEventListener('click', function(){ // respond to clicks on the login and logout links
FB.login(function(response){},{scope: 'friends_status,read_stream'});
});
}
</script>
Then this function executes when you click the button. It gets the User's last checked in location, and personal information including their facebook ID.
function getFriendsCheckin(token)
{
$.getJSON('https://api.foursquare.com/v2/checkins/recent?oauth_token='+token+'&v='+"20120514",function(results){
//console.log(results);
$.each(results['response']['recent'], function(key,value){
//console.log(key+' : '+value);
//Friends personal info
var fullName = value['user']['firstName']+" "+value['user']['lastName'];
var timeStamp = value['createdAt'];
var photo = value['user']['photo'];
var fbID = value['user']['contact']['facebook'];
//Where they last checked in
var locName = value['venue']['name'];
var location = new google.maps.LatLng(value['venue']['location']['lat'],value['venue']['location']['lng']);
//setMarker(location,fullName+'#'+locName);
setCustomMarker(location,fullName+'#'+locName,fbID,photo);
});
})
}
Lastly this is where the problem is. This function is suppose to show the user's friendd last status when the maker is clicked on google maps.
function setCustomMarker(location,title,fbID,icon)
{
//alert("here");
var marker = new google.maps.Marker({
position: location,
draggable: false,
map: map,
title: title,
//icon: icon
//icon: new google.maps.MarkerImage({url: icon, size: new google.maps.Size({width:10,height:10})})
});
google.maps.event.addListener(marker,'click',function(){
console.log('SELECT status_id,message FROM status WHERE uid='+fbID);
FB.api(
{
method: 'fql.query',
query: 'SELECT status_id,message FROM status WHERE uid='+fbID
},
function(response){
console.log(response);
}
);//*/
});
}
May be you are confused, but you can use fql with javascript sdk.
e.g.
FB.api(
{
method: 'fql.query',
query: 'SELECT name FROM user WHERE uid=me()'
},
function(response) {
alert('Your name is ' + response[0].name);
}
);
See reference
If you use graph api, this should work (not tested but you can check and updated me)
FB.api('/','POST',{
access_token:'<your_access_token>',
batch:[
{
"method": "GET",
"relative_url": "me/friends?limit=5",
"name": "get-friends"
},
{
"method": "GET",
"depends_on":"get-friends",
"relative_url": "{result=get-friends:$.data.*.id}/statuses"
}
]
},function(response){
console.log(response);
})
Ofcourse you need permission required for reading status updates of friends.
Try this:
FB.api('user_id/statuses','GET',{
//friends_status access token
});
Yes. It can be done with the help of graph API.
In the reference doc - take a look at the profile feed API call. There in that sample replace me with the user-id of the friend whose feed you are trying to access.
However, to do so via an app, you need to ask for read_stream and friends_status permissions from the user who is trying to use your app.
From my experience using client side Facebook js-sdk to handle OAuth is the easiest thing to do.
For the apps hosted on heroku, they provide sample implementation of client side OAuth handling and that is very useful. (To be able to host your app on heroku - while creating your app in developers.facebook.com/apps just make sure to choose "Host the project on Heroku" option.

facebook log-in API calls timing

Couldn't find similar enough question so I'll ask.
I'm trying to use facebook log-in on my page.
I did everything according the the developer's guides.
However, I'm not sure when I can start calling FB.API calls. when is the user authenticated? how can I know when this operation was done?
<script>
window.fbAsyncInit = function () {
FB.init({
appId: 'someID', // App ID
channelUrl: '//www.domain.com/channel.html', // Channel File
status: true, // check login status
cookie: true, // enable cookies to allow the server to access the session
xfbml: true // parse XFBML
});
};
// Load the SDK Asynchronously
(function (d) {
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) { return; }
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
} (document));
</script>
now I want to call this
FB.api('/me', function (response) {
facebookUser = response;
alert('Your name is ' + response.name);
});
but not sure when is the write time. I get undefined wherever I put it :/
You will want to run the FB.getLoginStatus() (https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/) before you send the user to log in using FB.login() or if the user is logged in, to call the FB.api() method.

Categories

Resources