Facebook API's FB object just seems to go null after init. This is the code I'm using, it's quite simple. The problem is that it says my "/me" response is undefined. I'm logged in, just double checked, so this is not the case. I already gave it permission to use my data.
Why is my "/me" responce undefined?
Also, is there a way I can move my code:
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
});
}
testAPI();
Into a separate .js file (with the code wrapped in a function), and have it load when function gets called inside window.fbAsyncInit? Cause every way I've tried to do that resulted in failure.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>FB-Stuff</title>
<link rel="stylesheet" href="style.css">
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '[my code]', // App ID
channelUrl : '//[my channel]', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
});
}
testAPI();
};
// 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>
</body>
</html>
edit-------------------------------------------------------
Now I'm not getting any function calls/error messages at all. This is the new code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>FB-Stuff</title>
<link rel="stylesheet" href="style.css">
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="mycode.js"></script>
</head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'xxx', // App ID
channelUrl : '//xxx/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
});
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
facebookInit();
}
});
};
// 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>
</body>
</html>
And inside mycode.js is:
function facebookInit(){
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
});
}
}
You need to defer the call to FB.api until after the status has been resolved - use FB.getLoginStatus or listen to one of the events for this.
Not sure what you mean with moving the code - you can put this code anywhere as long as it is loaded before the JS SDK.
Related
Using 'Facebook Login for the Web with the JavaScript SDK', I have a login button which works fine, i.e. user is logged in OK.(https://developers.facebook.com/docs/facebook-login/web#loginbutton).
However, the button does not change to the Logout button until I refresh the page. After refresh the logout button is displayed and when clicked reverts to login button as expected. Following is the full code which can be run from within IIS. I put it in my default web site and called http://localhost/aspnet_client/system_web/4_0_30319/test.html.
NOTE: Add your App Id where it says, ADD YOUR APP ID HERE.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div class="row margin-bottom-small">
<div id="login-button" class="fb-login-button" data-max-rows="1" data-size="xlarge" data-show-faces="false" data-auto-logout-link="true" onlogin="checkLoginState();"></div>
<div id="status"></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
function statusChangeCallback(response) {
console.log('statusChangeCallback');
console.log(response);
if (response.status === 'connected') {
testAPI();
}
}
function checkLoginState() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
window.fbAsyncInit = function() {
FB.init({
appId : 'ADD YOUR APP ID HERE',
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse social plugins on this page
version : 'v2.8' // use graph api version 2.8
});
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;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
// Here we run a very simple test of the Graph API after login is
// successful. See statusChangeCallback() for when this call is made.
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Successful login for: ' + response.name);
document.getElementById('status').innerHTML =
'Thanks for logging in, ' + response.name + '!';
});
}
</script>
</body>
</html>
FB code is from https://developers.facebook.com/docs/facebook-login/web#example
I don't want to refresh the page programatically. It is a single page application and refreshing the page will take me to the start.
Thanks.
Well, I couldn't figure out why it wouldn't refresh automatically - perhaps that by design. Here is my workaround - basically add the logout button and call FB.logout myself. If someone from Facebook dev team can provide a more elegant solution, I'd love to know. Thanks.
NOTE: Add your App Id where it says, ADD YOUR APP ID HERE.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div class="row margin-bottom-small">
<div id="login-button" class="fb-login-button" data-max-rows="1" data-size="small" data-show-faces="false" data-auto-logout-link="false" onlogin="checkLoginState();"></div>
<div hidden id="logout-button" class="fb-login-button" data-max-rows="1" data-size="small" data-show-faces="false" data-auto-logout-link="false" onlogin="logout();">Log Out</div>
<div id="status"></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
function statusChangeCallback(response) {
console.log('statusChangeCallback');
console.log(response);
if (response.status === 'connected') {
testAPI();
} else {
// The person is not logged into your app or we are unable to tell.
//document.getElementById('status').innerHTML = 'Please log into this app.';
document.getElementById('login-button').style.display = 'block';
document.getElementById('logout-button').style.display = 'none';
}
}
function checkLoginState() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
function logout() {
FB.logout(function (response) {
document.getElementById('logout-button').style.display = 'none';
document.getElementById('login-button').style.display = '';
document.getElementById('status').innerHTML = 'You have been logged out!';
});
}
window.fbAsyncInit = function() {
FB.init({
appId : 'ADD YOUR APP ID HERE',
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse social plugins on this page
version : 'v2.8' // use graph api version 2.8
});
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;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
// Here we run a very simple test of the Graph API after login is
// successful. See statusChangeCallback() for when this call is made.
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Successful login for: ' + response.name);
document.getElementById('login-button').style.display = 'none';
document.getElementById('logout-button').style.display = 'block';
document.getElementById('status').innerHTML = 'Thanks for logging in, ' + response.name + '!';
});
}
</script>
</body>
</html>
UPDATED.
This code block takes the users facebook connections and saves them into the "fbdata" and within the div "friends-list-container".
Here is the page with the error.
I'm then attempting to save the data to parse.com and have the following error shown the image below.
<!doctype html>
<!-- Runs Parse and FB code that uses Facebook authentication to login
user to the site and redirects them to the main content area. This page is
fired from the Facebook button being clicked on the site landing page-->
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="fresh Gray Bootstrap 3.0 Responsive Theme "/>
<meta name="keywords" content="Template, Theme, web, html5, css3, Bootstrap,Bootstrap 3.0 Responsive Login" />
<meta name="author" content="Adsays"/>
<title>Parse JavaScript Todo App</title>
<script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<script src="scripts/underscore-1.1.6.js"></script>
<script src="http://www.parsecdn.com/js/parse-1.2.13.min.js"></script>
</head>
<body>
<!-- Important, must be on the page -->
<div id="fb-root"></div>
<!-- Initialize the Parse object-->
<script type="text/javascript">
Parse.initialize("79tphN5KrDXdjJnAmehgBHgOjgE2dLGTvEPR9pEJ", "9lblofQNZlypAtveU4i4IzEpaOqtBgMcmuU1AE6Y");
var user = Parse.User.current();
//Fb app information//
window.fbAsyncInit = function() {
Parse.FacebookUtils.init({
appId : '523753101076577',
channelUrl : 'http://www.kudosoo.com/channel.html',
status : true,
cookie : true,
xfbml : true
});
//FB user authentication script, after this completes it fires todos_two.js to redirect user to main content page//
FB.getLoginStatus(function (response) {
if (response.status === 'connected') {
FB.api('/me/friends', function(response){
if (response && response.data){
var contact = new Parse.User();
var fbdata=response.data;
var divTarget=document.getElementById("friends-list-container");
for (var friendIndex=0; friendIndex<fbdata.length; friendIndex++)
{ var divContainer = document.createElement("div");
divContainer.innerHTML="<b>" + fbdata[friendIndex].name + "</b>";
divTarget.appendChild(divContainer);
}
var contact = new Parse.User();
var contact = new Contact();
$(document).ready(function () {
var username = $("#friends-list-container").val();
contact.set("facebookFriends", fbdata.toString());
contact.save(null, {
success: function (results) {
// The object was saved successfully.
location.reload();
},
error: function (contact, error) {
// The save failed.
// error is a Parse.Error with an error code and description.
alert("Error: " + error.code + " " + error.message);
}
});
});
} else {
console.log('Something goes wrong', response);
}
});
}
});
};
(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/all.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
<div id="friends-list-container"></div>
</body>
</html>
Here is the error.
Try replacing this line:
var contact = Parse.Object.extend("_User");
Updated from the chat conversation, this is what solved the problem:
If you want to store the friends list in an array on the current user, then Parse.User.current() is what you want:
var contact = Parse.User.current()
I'm trying to get user information from facebook without sucess, someone can show me how and where should I put it in my code?
I already try using FB.getLoginStatus and some others that facebook tutorials had, I think I'm not knowing where to put it in my code...
I got to do this util the end of the mount, but I had never worked it html and javascript before.. so please help me guys!
thank you very much!
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="text/html; charset=utf-8">
<title>SlickQuiz Demo</title>
<link href="css/reset.css" media="screen" rel="stylesheet" type="text/css">
<link href="css/slickQuiz.css" media="screen" rel="stylesheet" type="text/css">
<link href="css/master.css" media="screen" rel="stylesheet" type="text/css">
<link href="css/jquery.mobile-1.3.1.min.css" rel="stylesheet" type="text/css">
</head>
<body id="slickQuiz">
<div data-role="header">
<h1 class="quizName"><!-- where the quiz name goes --></h1>
</div>
<div data-role="content" class="quizArea">
<div class="quizHeader">
<!-- where the quiz main copy goes -->
<a class="button startQuiz" data-role="button" href="#" data-theme="b">Iniciar o teste!</a>
</div>
<!-- where the quiz gets built -->
</div>
<div class="quizResults">
<h3 class="quizScore">Pontuação: <span><!-- where the quiz score goes --></span></h3>
<h3 class="quizLevel"><strong>Nível:</strong> <span><!-- where the quiz ranking level goes --></span></h3>
<div class="quizResultsCopy">
<!-- where the quiz result copy goes -->
</div>
</div>
<script src="js/jquery.js"></script>
<script src="js/slickQuiz-config.js"></script>
<script src="js/slickQuiz.js"></script>
<script src="js/master.js"></script>
<fb:login-button show-faces="true" width="200" max-rows="1" perms="user_hometown,user_about_me,email,user_address" autologoutlink="true"></fb:login-button>
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '245686095571989', // App ID
channelUrl : 'http://localhost:8080/SlickQuiz/', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse XFBML
oauth : true
});
FB.api('/me', function(response) {
alert(response.name);
});
FB.Event.subscribe('auth.authResponseChange', function(response) {
if (response.status === 'connected') {
testAPI();
} else if (response.status === 'not_authorized') {
FB.login();
} else {
FB.login();
}
});
};
(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));
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
alert('3');
console.log('Good to see you, ' + response.name + '.');
alert(response.name);
});
}
</script>
</body>
</html>
Hmmm, there are multiple things in the above code which I don't understand why you need it there. For one, is there a reason why you gave oauth to true? Are you using oauth?
I tried to port this to a jsfiddle page to show you the working code but FB does block the usage of APPIDs outside the domain. This should give you an idea of what you needed: http://jsfiddle.net/7Ekz9/
window.fbAsyncInit = function () {
FB.init({
appId: '245686095571989', // App ID
status: true, // check login status
cookie: true, // enable cookies to allow the server to access the session
xfbml: true
});
FB.login(function (response) {
console.log(response);
if(response.authResponse){
testAPI();
}
});
};
FYI: I loaded the all.js as a external resource. You may try that as well.
I have tried countless examples from all around.. Is there any real way to get the current users name in a fan page app using the JavaScript sdk without a pop up requesting authentication?
Here is my current JS:
window.fbAsyncInit = function() {
FB.init({
appId : 'ID', // App ID
channelUrl : 'url/channel.php', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
frictionlessRequests : true, // enable frictionless requests
xfbml : true // parse XFBML
});
// Additional initialization code here
FB.api('/me', function(response) {
console.log("Welcome " + response.name);
});
};
// Load the JavaScript 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));
and then my PHP:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:og="http://ogp.me/ns#">
<head>
<meta charset="utf-8" />
<title>View Source App</title>
<script type="text/javascript" src="script/jquery.min.js"></script>
<script type="text/javascript" src="script/script.js"></script>
</head>
<body>
<div id="fb-root"></div>
<div id="content">
<h2>My First App</h2>
<p>This is some text to make sure my app is working on Facebook</p>
</div><!--content -->
</body>
</html>
Any Help Greatly Appreciated.
The short answer is no. You need permission to access any user data.
Here is my code
<html>
<head>
<head>
<title></title>
<script type="text/javascript" charset="utf-8" src="cordova-1.6.0.js"></script>
<script type="text/javascript">
function go()
{
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.');
}
});
}
</script>
<body>
<div id="fb-root">
</div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '', // App ID
channelUrl : '', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse XFBML
oauth : true //oauth v2.0
});
};
// 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));
</script>
<input onclick="go();" type='submit' id='login-button' value='Login' name='login' >
</body>
</html>
Basically you click the button and it should show you a login pop-up. It works when I try in a normal browser but when I try in the iPhone simulator nothing happens. Iv also set the iPhone browser to allow pop-ups. what am I doing wrong?
I got it working using the phonegap plugin called Childbrowser :)