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.
Related
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
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.
I've been racking my brains for ages now on this problem. After loading the JavaScript SDK I cannot make any GET calls to the the graph API. I'm attempting to use /me/home but I've tried /me as well for debugging purposes. The strange thing is, if I check the user's login status it return's an access token which I can use to retrieve the news feed perfectly in the address bar. However, as soon as I make a GET call to the Graph API using JavaScript I get:
"An active access token must be used to query information about the current user."
Also I can make POST call the the user's feed using SDK perfectly fine. Finally, I have checked to make sure I have the read_stream permission.
window.fbAsyncInit = function() {
FB.init({
appId : '<?php echo($facebook_key); ?>', // App ID
channelUrl : '//'+window.location.hostname+'/channel.php', // 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
console.log(response);
} else {
location.href='welcome.php';
};
});
FB.getLoginStatus(function(response) {
console.log(response);
});
//get Facebook news feed
FB.api('/me/home', 'get', function(response) {
console.log(response);
});
};
// 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));
//status update function
function post (form) {
var status = form.status.value;
FB.api('/me/feed', 'post', { message: status }, function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Status updated');
};
});
};
I would try moving your call to /me into your FB.getLoginStatus function:
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
//get Facebook news feed
FB.api('/me/home', 'get', function(response) {
console.log(response);
});
}
});
I think the issue is, your call to the api is firing before the authentication is confirmed. Hopefully moving this function into the getLoginStatus callback should resolve this issue.
You can see more examples here https://developers.facebook.com/tools/console/
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.
My App on Facebook uses the JavaScript SDK. When a user navigates to my app page and goes to my app, a popup asks them to authorize the app. This works well.
However, if they authorize the app, then return to it later, another pop-up (which i believe to be another authorization window) will quickly open then close.
What is my code is doing this? Code is below.
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '221953271200525', // App ID
channelURL : '//www.vidjahgames.com/fall/channel.html', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
oauth : true, // enable OAuth 2.0
xfbml : true // parse XFBML
});
// Additional initialization code here
FB.login(function(response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, {scope: 'email'});
};
// 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>
FB.login makes the popup appear, so you should first know if the user is logged in and if not make the login popup appear:
FB.getLoginStatus(function(response) {
if (response.session) {
// A user has logged in, and a new cookie has been saved
FB.api('/me', function(response) {
_userName = response.name;
alert("hello"+_userName);
}.bind(this));
} else {
FB.login(function(response) {
// the rest of your code here...
}
}
});