How to get user feeds from facebook using angular js. - javascript

I had referred many articles but It couldnt solve this issue. Im trying to get the user feeds from facebook.How can i get it.
Here is my code:
var newMod = angular.module('newapp', []);
newMod.controller('mainCtrl', function ($scope) {
window.fbAsyncInit = function () {
//SDK loaded, initialize it
FB.init({
appId: 'your app id',
xfbml: true,
version: 'v2.3'
});
//check user session and refresh it
FB.getLoginStatus(function (response) {
if (response.status === 'connected') {
//user is authorized
document.getElementById('loginBtn').style.display = 'none';
getUserData();
} else {
//user is not authorized
}
});
function getUserData() {
FB.api('/me', function (response) {
document.getElementById('response').innerHTML = 'Hello ' + response.name;
document.getElementById('dialog_div').style.border = '1px solid red';
document.getElementById('dialog_div').innerHTML = response;
});
}
};
//load the JavaScript SDK
(function (d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) { return; }
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
$scope.loginClick = function () {
FB.login(function (response) {
if (response.authResponse) {
//user just authorized your app
document.getElementById('loginBtn').style.display = 'none';
getUserData();
}
}, { scope: 'email,public_profile', return_scopes: true });
}
});
my html code:
<body ng-app="newapp">
<div ng-controller="mainCtrl">
<button id='loginBtn' ng-click="loginClick()" >FacebookLOGin</button>
<div id="response"></div>
<div id="dialog_div"></div>
</div>
from getuserdata() Im able to get the user details. Now how to access the user feeds. I had tried to use the below code but it outputs empty array.
FB.api("/me/feed",function(response){
if(response !="" ){
// access the feed data
}
})
Can anyone explain me the way to get the user feeds after user login.

I got to know the mistake that was done.
Here the session will be expired when the person tries to access the feeds.
So include the FB.api('/me/feed',function(response){}) in the code section FB.login(function(response) {})
Now the session will be able to access the userfeeds.

Your app needs the user_posts to get the user's feed. The /user/feed doc explains that pretty well. In any case, you need to implement facebook login, ask for user_posts permission from your user and go from them to get the user's feed.

Related

Api of facebook is blinking when getting user information

Currently make the connection to the facebook api with php, create a project in facebook developers, generate the corresponding keys and as for the permissions of users I'm using the default and the permission of the mail, allows me to enter and give permission to the application but sometimes does not bring all the user information and some times when you click the button facebook does not open the popup to log in with facebook or give permission to the application with my account, sometimes if not, I do not know why and the case is still very intermittent, in the browser console does not tell me that is due to the intermittence, something important to mention is that the day if there is a high flow of people trying to use the login with facebook but the intermittent can not be logged in, I have this script in html before the body:
window.fbAsyncInit = function () {
FB.init({
appId: '<?php echo $UrlApiFacebook; ?>',
cookie: true, // Enable cookies to allow the server to access the session.
autoLogAppEvents : true,
xfbml: true, // Parse social plugins on this webpage.
version: 'v7.0' // Use this Graph API version for this call.
});
};
(function(d, s, id) { // Load the SDK asynchronously
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "https://connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
function checkLoginState() {
FB.getLoginStatus(function (response) { // Called after the JS SDK has been initialized.
statusChangeCallback(response, 1); // Returns the login status.
});
}
For this code I rely directly on the official documentation of facebook developer, in another javascript file is the function 'statusChangeCallback()' this file is like this:
function statusChangeCallback(response, i) {
console.log('statusChangeCallback');
console.log(response);
if (i == 3) {
if (response.status === 'connected') { // Logged into your webpage and Facebook.
FB.logout(function (response) {
window.location.href = "login_out.php";
});
} else {
window.location.href = "login_out.php";
}
} else {
if (response.status === 'connected') { // Logged into your webpage and Facebook.
testAPI();
} else { // Not logged into your webpage or we are unable to tell.
console.log("No logueado");
FB.login(function (response) {
if (response.status === 'connected')
testAPI();
});
}
}
}
function testAPI() { // Testing Graph API after login. See statusChangeCallback() for when this call is made.
console.log('Welcome! Fetching your information.... ');
FB.api('/me', { fields : 'name,picture,first_name,last_name,email' }, function (response) {
console.log('Successful login for: ' + response.name);
onSendDataFacebook(response);
});
}
function logoutUserFacebook() {
FB.getLoginStatus(function (response) { // Called after the JS SDK has been initialized.
statusChangeCallback(response, 3); // Returns the login status.
});
}
function onSendDataFacebook(userFacebook) {
let email = "";
let name = "";
let last_name = "";
var user = {
id: userFacebook.id, nombre: userFacebook.name,
email: userFacebook.email,
nombrecompleto: userFacebook.first_name + ' ' + userFacebook.last_name,
llamado: redir,
veces: x
}
if(!userFacebook.email){
user.email = email;
}
if(!userFacebook.name){
user.name = name;
}
if(!userFacebook.first_name || !userFacebook.last_name){
user.first_name = name;
user.last_name = last_name;
}
redireclogin(user);
}
I would very much appreciate the help of anyone who knows what this intermission is about, thank you in advance.

Uncaught TypeError: FB.login is not a function

I am Using Facebook JavaScript API to create login with feature with Facebook and fetch the user details from the API.
When I am using the same code in normal way, I am getting the data fetched from from Facebook api.
When I try to do the same thing with requireJS, I am Getting this error
"Uncaught TypeError: FB.login is not a function"
I have seen errors like undefined function but this new to me.
The format which I am following
https://developers.facebook.com/docs/javascript/howto/requirejs/v2.7
and my code fb.js goes here
define(['jquery','facebook'], function($,FB){
window.fbAsyncInit = function() {
FB.init({
appId : '89080988080545753578',
oauth : true,
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true ,// parse XFBML
version : 'v2.5'
});
};
window.fb_login = function(){
FB.login(function(response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
//console.log(response); // dump complete info
access_token = response.authResponse.accessToken; //get access token
user_id = response.authResponse.userID; //get FB UID
FB.api('/me', function(response) {
user_email = response.email; //get user email
$("#name").val(response.name);
$("#user-id").val(response.id);
if(response.gender == 'male') {
$('input[name="gender"][value="female"]').attr('checked', false);
$('input[name="gender"][value="male"]').attr('checked', true);
} else {
$('input[name="gender"][value="male"]').attr('checked', false);
$('input[name="gender"][value="female"]').attr('checked', true);
}
$("#birthday").val(response.birthday);
$("#email").val(response.email);
// you can store this data into your database
});
} else {
//user hit cancel button
console.log('User cancelled login or did not fully authorize.');
}
}, {
scope: 'publish_stream,email'
});
};
});
and the html code for the button click
<button type="button" class="btn btn-lg btn-block sm fb" value="Login" id="FB">Facebook</button>
and JS code for the click event
$( document ).ready(function() {
$(".btn").click(function(){
//getting button id value in variable
var method = $(this).attr('id');
$("#sign_method").val(method);
if(method == 'FB') {
alert('Facebook');
fb_login();
//fbData();
//$("#signup").submit();
} else if(method == 'GP') {
alert('Google Plus');
login();
// $("#signup").submit();
} else {
alert('Email');
$("#signup").remove();
alert('form removed');
window.location.href = "signup.html";
}
});
The error message means that the JS SDK is not loaded yet. You are missing this in your code:
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
FB.login must be used AFTER FB.init. Make sure FB.init gets called.
More information: http://www.devils-heaven.com/facebook-javascript-sdk-login/
For RequireJS, this would be the official way to include the JS SDK: https://developers.facebook.com/docs/javascript/howto/requirejs/v2.7#adding-a-shim-to-the-facebook-sdk
In my case, I had an adblocker extension that was preventing SDK from initializing properly. I only realized after trying in a different browser that didn't have adblocker extension

Get facebook friends list in js using graph API

I have created an app on Facebook. I want to refer that app to a friend so for that I want to display the list of friends. I'm getting only user info but not the friend list.
I have used the below code, please help me get the friend list.
window.fbAsyncInit = function() {
FB.init({
appId : 'xxxxxxxxxxxxxxxxxxx',
xfbml : true,
version : 'v2.4'
});
function onLogin(response) {
if (response.status == 'connected') {
FB.api('/me?fields=first_name', function(data) {
var welcomeBlock = document.getElementById('fb-welcome');
welcomeBlock.innerHTML = 'Hello, ' + data.first_name + '!';
});
}
}
FB.getLoginStatus(function(response) {
// Check login status on load, and if the user is
// already logged in, go directly to the welcome message.
if (response.status == 'connected') {
onLogin(response);
} else {
// Otherwise, show Login dialog first.
FB.login(function(response) {
onLogin(response);
}, {scope: 'user_friends, email'});
}
});
};
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
function getFriends() {
alert("in friends");
FB.api('/me/friends', 'GET',{},
function(response) {
if (response.data) {
console.log(response.data);
$.each(response.data,function(index,friend) {
console.log(friend.name +'has id:'+friend.id);
// alert(friend.name);
});
} else {
alert("Error!");
}
});
}
You don't even request the friends in your code. Since Graph API v2.0, you'll only receive the friends which are also using your app, and not all friends.
Use
FB.api('/me?fields=first_name,friends', function(data) { ... });
In App Friends
FB.api("/me/friends",function(res) {
console.log(res)
});
doc
Inviable Friends(only in Game)
FB.api("/me/invitable_friends",function(res){
console.log(res)
});
doc

jquery get dynamic span id value

I have added facebook SDK in my web project, and i am printing all the values through id but i have one doubt.How to get the dynamic id value through jquery or javascript.
My Code
FB.api('/me', function(response) {
console.log('Successful login for: ' + response.name);
var fullname = document.getElementById('admin_name').innerHTML = response.name;
});
//Displaying through html
<span id="admin_name"></span> and it's printing successfully.
But when i wants to get the id value through jquery or javascript it's coming null or empty.
//Jquery Code
$(document).ready(function () {
var adminName = $("#admin_name").text();
alert(adminName);
});
My Complete Login As Facebook Code
function statusChangeCallback(response)
{
console.log(response);
if (response.status === 'connected') {
testAPI();
}
}
function checkLoginState() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
window.fbAsyncInit = function() {FB.init({
appId : '12345678910',
cookie : true,
xfbml : true,
version : 'v2.2'
});
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
};
// Load the SDK asynchronously
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id))
return;
js = d.createElement(s);
js.id = id;
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
function testAPI() {
FB.api('/me', function(response) {
var fullname = document.getElementById('admin_name').innerHTML = response.name;
});
}
And Calling through FB Login Button
<fb:login-button max_rows="1"
size="large"
show_faces="false"
auto_logout_link="false"
onlogin="checkLoginState();">Login with Facebook
</fb:login-button>
Your problem is one of timing. The dom is going to grab what value is currently there, not one that will be there soon. At the time $(document).ready is called, your FB.api has not. Therefore, it will return null. Call the function after your FB.api is called.
Programmatically:
Stick your alert code in a function
alertMe = function(){
$(document).ready(function () {
var adminName = $("#admin_name").text();
alert(adminName);
});
}
and call that function when your FB API is done doing its thing
FB.api('/me', function(response) {
console.log('Successful login for: ' + response.name);
var fullname = document.getElementById('admin_name').innerHTML = response.name;
alertMe(); //send the call for the alert
});

Track canceled facebook login

I wish to track users which were presented with the Facebook Login dialog popup, and chose to close it (by clicking "cancel" or just closed the popup window).
I am using Facebook SDK and invoking FB.login()
From the docs it's unclear, but it does appear there might be some way to track this, so, if anyone here knows how, or can help, it would be appriciated. Thanks!
complete code:
var facebook = (function(){
// Configuration
var serverDomain = '365scores.com',
appID = '158698534219579';
// Load the SDK asynchronously
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
window.fbAsyncInit = function(){
FB.init({
appId : appID,
cookie : true, // enable cookies
xfbml : true, // parse social plugins on this page
version : 'v2.0' // use version 2.0
});
FB.getLoginStatus(FBLoginStatus);
FB.Event.subscribe('auth.authResponseChange', FBLoginStatus);
};
function FBLoginStatus(response){
// The response object is returned with a status field that lets the
// app know the current login status of the person.
// Full docs on the response object can be found in the documentation
// for FB.getLoginStatus().
if( response.status === 'connected' ){
// Logged into your app and Facebook.
//connected(response);
$(document).trigger('connection', ['facebook', response]);
}
else if( response.status === 'not_authorized' ){
// The person is logged into Facebook, but not your app.
}
else{
// The person is not logged into Facebook, so we're not sure if
// they are logged into this app or not.
}
};
function checkLoginState() {
FB.getLoginStatus(function(response) {
FBLoginStatus(response);
});
}
function connected(res){
console.log( res )
console.log('FACEBOOK CONENCTED');
/*
FB.api('/me', function(response){
});
*/
}
return FBLoginStatus;
})();
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.');
}
});

Categories