I am trying to add events information to the facebook users profile from a 3rd party website using Javascript SDK provided by facebook. I just googled for few tutorials and I got this links
http://thinkdiff.net/facebook/graph-api-javascript-base-facebook-connect-tutorial/
http://www.masteringapi.com/tutorials/how-to-ask-for-extended-permission-in-your-facebook-application/32/
http://www.masteringapi.com/tutorials/how-to-create-facebook-events-using-graph-api/49/#using_the_js-sdk
I tried with the combination of login logout and session handling
this is the code which I am run just to test whether it works or not.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<div id="fb-root"></div>
<script type="text/javascript">
window.fbAsyncInit = function()
{
FB.init({
appId: '207712505927107',
status: true,
cookie: true,
xfbml: true
});
/* All the events registered */
FB.Event.subscribe('auth.login', function(response) {
// do something with response
login();
});
FB.Event.subscribe('auth.logout', function(response) {
// do something with response
logout();
});
FB.getLoginStatus(function(response)
{
if (response.session)
{
// logged in and connected user, someone you know
login();
}
});
};
(function()
{
var e = document.createElement('script');
e.type = 'text/javascript';
e.src = document.location.protocol
+ '//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
function login()
{
FB.api('/me', function(response)
{
document.getElementById('login').style.display = "block";
var loggedInMessage = response.name + " successfully logged in!";
document.getElementById('login').innerHTML = loggedInMessage;
});
}
function logout()
{
document.getElementById('login').style.display = "none";
}
//addevent to facebook profile
function addevents()
{
FB.api('/me/events', 'post', {
name: "JS-SDK Event",
start_time: 1272718027,
location: "Beirut",
privacy_type: "OPEN"
}, function(resp) {
alert(resp.id);
});
}
</script>
<p>
<fb:login-button
autologoutlink="true"
perms="email,user_birthday,status_update,publish_stream,create_event">
</fb:login-button>
</p>
<p>
Add Events
</p>
<br />
<br />
<br />
<br />
<div id="login" style ="display:none"></div>
<div id="name"></div>
</body>
</html>
When I click on the add event page I am getting "undefined". Iam not able to add events to facebook profle. Kindly help me
I would try your code again, and maybe console.log(resp) in your callback method for the addevents function. I tested your code on fbrell.com and it seemed to work perfectly and as expected.
edit: after a little research (and your fixed code..) I found that the fb:login button doesn't ensure that your application has the correct permissions that the perms parameter requests. We find this out when we do a Graph request and it fails. So we catch the error, and then launch the Login modal via the FB.login method, and ask for the create_event permission. When the user accepts that dialog, we retry creating the event.
<fb:login-button
autologoutlink="true"
perms="email,user_birthday,status_update,publish_stream,create_event">
</fb:login-button>
create
<script>
FB.XFBML.parse();
document.getElementById('create_event').onclick = function() { create_event(); }
function create_event()
{
FB.api('/me/events', 'post', {
name: "JS-SDK Event",
start_time: 1272718027,
location: "Anywhere USA",
privacy_type: "OPEN"
}, function(resp) {
if (typeof resp.error != 'undefined')
{ /*this failed. most likely because we don't have the extended permission
for create_event. so lets check for it, ask for it, and try to create
the event again. but first, we'll make sure that the error message says
something about 'create_event' so we don't launch an infinite loop
*/
if (resp.error.message.match(/create_event/))
{
FB.login(function(response)
{
if (response.session
&& response.status == 'connected'
&& response.perms.match(/create_event/))
{
//this user is connected & we have create event permission.
create_event();
}
},
{
perms: 'create_event'
});
}
}
});
}
</script>
Working code on fbrell.com: http://fbrell.com/saved/17c7b60eab91e6736a2a10c87d53c5b8
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<div id="fb-root"></div>
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({appId: '207712505927107', status: true, cookie: true, xfbml: true});
/* All the events registered */
FB.Event.subscribe('auth.login', function(response) {
// do something with response
login();
});
FB.Event.subscribe('auth.logout', function(response) {
// do something with response
logout();
});
FB.getLoginStatus(function(response) {
if (response.session) {
// logged in and connected user, someone you know
login();
}
});
};
(function() {
var e = document.createElement('script');
e.type = 'text/javascript';
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
function login(){
FB.api('/me', function(response) {
document.getElementById('login').style.display = "block";
document.getElementById('login').innerHTML = response.name + " succsessfully logged in!";
});
}
function logout(){
document.getElementById('login').style.display = "none";
}
//add events
function addevents() {
FB.api('/me/events','post',{
name:"awesome event",
start_time:1272718027,
location:"Bengaluru",
privacy_type:"OPEN",
description:"U r invited !!!"
}, function(resp) {
document.write(resp.id);
});
}
//checking persmission
function check_perm() {
FB.api({ method: 'users.hasAppPermission', ext_perm: 'create_event' }, function(resp)
{
if (resp === "1") {
alert('Permission granted');
} else {
alert("Permission not granted");
}
});
}
</script>
<p>Please click on Login button first </p>
<p><fb:login-button autologoutlink="true" perms="create_event"></fb:login-button></p>
<p> Please click on check permissions first </p>
check permissions
<p> now u r all set to add events to facebook </p>
<p>
Add Events
</p>
<br /><br /><br />
<div id="login" style ="display:none"></div>
<div id="name"></div>
</body>
</html>
Related
Here i am doing Login with facebook,and also it is working fine,now my question is after login i need the profile pic path,i don't how can get the path,if any one knows please update your answer.as od now i am getting the values like id,name,email but i don't the profilepic path
window.fbAsyncInit = function() {
FB.init({appId: '1990039811315283', status: true, cookie: true, xfbml: true});
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
function fetchUserDetail()
{
FB.api('/me?fields=id,name,email', function(responseFromFB){
//console.log("Name: "+ response.name + "\Email: "+ response.email + "ID: "+response.id);
console.log(JSON.stringify(responseFromFB));
var userName = responseFromFB.name;
var userEmail = responseFromFB.email;
var profilePic = '1.png';
var registerFrom = 'Web';
var FCM_Token = '';
$.ajax({
url:'admin/rest/registerFB',
type:'POST',
data: {userName: userName, userEmail: userEmail, profilePic: profilePic, registerFrom: registerFrom, FCM_Token: FCM_Token},
success:function(loginResponse){
if(loginResponse['status']=='success'){
window.location.href = "index.php";
}
},
});
});
}
function checkFacebookLogin()
{
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
fetchUserDetail();
}
else
{
initiateFBLogin();
}
});
}
function initiateFBLogin()
{
FB.login(function(response) {
fetchUserDetail();
}, {scope: 'email'});
}
<html>
<head>
<title>Facebook Login JavaScript Example</title>
<meta charset="UTF-8">
</head>
<body>
<input type="button" class="btn btn-lg btn-fb" value="Sign in using Facebook" scope="public_profile,email" onclick="checkFacebookLogin();"/>
<div id="fb-root"></div>
When you get the response from FB, you'll get the id of the user for your registered App. You can use this id and get the image of the user.
The below code creates an image tag dynamically and adds to the body. add this to your fetchUserDetail() response handler.
let image = document.createElement("img");
image.src = `https://graph.facebook.com/v2.12/${responseFromFB.id}/picture`;
document.body.appendChild(image);
API docs here
I have followed
https://developers.google.com/identity/sign-in/web/sign-in
and
https://developers.google.com/identity/sign-in/web/build-button
but once login it automatically logins.
I want button after clicking it fetch Gmail information in javascript function==> from javascript function redirect to another db_validation page to validate with the database if a user exists ==> if successful go to welcome page or go back to main login page.
please help me out I am unable to find proper resources.
I am using JSP, Javascript.
<script src="https://apis.google.com/js/client:platform.js?onload=renderButton" async defer> </script>
function onSuccess(googleUser) {
var profileinfo = googleUser.getBasicProfile();
console.log('---------------------------------------');
console.log('ID: ' + profileinfo.getId());
console.log('Name: ' + profileinfo.getName());
console.log('Image URL: ' + profileinfo.getImageUrl());
console.log('Email: ' + profileinfo.getEmail()); //
window.location.href = 'login.jsp?name =profile.getName()';
}
function onFailure(error) {
alert(error);
}
function renderButton() {
gapi.signin2.render('gSignIn', {
'scope': 'profile email',
'width': 580,
'height': 75,
'longtitle': true,
'theme': 'dark',
'onsuccess': onSuccess,
'onfailure': onFailure
});
}
function signOut() {
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
$('.userContent').html('');
$('#gSignIn').slideDown('slow');
$('#normalSignIn').slideDown('slow');
});
}
<div class = "connect" id="gSignIn"></div>
I got answer, posting Here may be helpful to other.
Login.jsp:-
<div class = "connect" id="gSignIn"></div>
LoginBackend.jsp:-
**<%# page langu**age="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.sql.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login</title>
</head>
<body>
<%! String userdbName;
String userdbPsw;
String dbUserEmail;
%>
<%
Connection con= null;
PreparedStatement ps = null;
ResultSet rs = null;
String driverName = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/logindb";
String user = "root";
String dbpsw = "root";
String sql = "select * from userdetail where email=? and password=?";
String entered_name,entered_email, entered_password ;
//from form values
entered_email = request.getParameter("email");
entered_password = request.getParameter("password");
if(((entered_email!= (null) ||entered_email !=("")) && (entered_password !=(null) || entered_password !=(""))))
{
try{
Class.forName(driverName);
con = DriverManager.getConnection(url, user, dbpsw);
ps = con.prepareStatement(sql);
ps.setString(1, entered_email);
ps.setString(2, entered_password);
rs = ps.executeQuery();
if(rs.next())
{
userdbName = rs.getString("name");
dbUserEmail = rs.getString("email");
userdbPsw = rs.getString("password");
if(entered_email.equals(dbUserEmail) && entered_password.equals(userdbPsw) )
{
session.setAttribute("name",userdbName);
session.setAttribute("email",dbUserEmail);
session.setAttribute("login_type","normal");
response.sendRedirect("welcome.jsp");
}
}
else
{
response.sendRedirect("error.jsp");
}
rs.close();
ps.close();
}
catch(SQLException sqe)
{
out.println(sqe);
}
}
else
{
%>
<center><p style="color:red">Error In Login</p></center>
<%
getServletContext().getRequestDispatcher("/home.jsp").include(request,
response);
}
%>
</body>
Welcome.JSP:-
!-- this google client id id for localhost -->
<meta name="google-signin-client_id" content="1015753179876-pphemvpb1o83nakb94s6na33pcjl33l8.apps.googleusercontent.com">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome</title>
<script>
function signOut() {
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
console.log(gapi.auth2.getAuthInstance().isSignedIn);
console.log('User signed out.');
alert("Sign out..");
auth2.disconnect();
window.location.href = "logout.jsp";
});
}
function onLoad() {
gapi.load('auth2', function() {
gapi.auth2.init();
});
}
function facebook_logout()
{
FB.logout(function(response)
{
/* alert("log out 1 " + response);
*/ FB.getLoginStatus(function(response)
{
if (response && response.status === 'connected')
{
alert("log out " + response);
FB.logout(function(response) {
alert("log out ");
document.location.reload();
window.location.href = "logout.jsp";
});
}
});
window.location.href = "logout.jsp";
});
}
</script>
</head>
<body>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '323155731439231',
apiKey : '323155731439231',
cookie : true, // enable cookies to allow the server to access
status : true, // the session
xfbml : true, // parse social plugins on this page
version : 'v2.9' // use graph api version 2.8
});
// Now that we've initialized the JavaScript SDK, we call
// FB.getLoginStatus(). This function gets the state of the
// person visiting this page and can return one of three states to
// the callback you provide. They can be:
//
// 1. Logged into your app ('connected')
// 2. Logged into Facebook, but not your app ('not_authorized')
// 3. Not logged into Facebook and can't tell if they are logged into
// your app or not.
//
// These three cases are handled in the callback function.
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
};
// This is called with the results from from FB.getLoginStatus().
function statusChangeCallback(response) {
console.log('statusChangeCallback');
console.log(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.
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.';
}
}
// This function is called when someone finishes with the Login
// Button. See the onlogin handler attached to it in the sample
// code below.
function checkLoginState() {
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.... ');
/* alert("testapi"); */
FB.api('/me?fields=id,name,email,permissions', function(response) {
console.log('Successful login for: ' + response.name);
console.log(response.email);
});
}
</script>
<%-- <p>Welcome, <%=session.getAttribute("name")%></p> --%>
<%
if(session.getAttribute("login_type")=="google")
{
System.out.println("welcome by google");
out.println("Welcome, " + session.getAttribute("name"));
%>
Sign out by google
<%
}
else if(session.getAttribute("login_type")=="normal")
{
out.println("Welcome, " + session.getAttribute("name"));
%>
Logout_Normal
<%
}
else if(session.getAttribute("login_type")=="facebook")
{
System.out.println("welcome by facebook");
out.println("Welcome, " + session.getAttribute("name"));
%>
Sign out by facebook
<%
}
else
{
response.sendRedirect("home.jsp");
}
%>
<script src="https://apis.google.com/js/client:platform.js?onload=onLoad" async defer> </script>
<script src="js/jquery.min.js"></script>
</body>
</html>
I am trying to get Users login status with facebook js sdk. Script works fine when i load it without any onclick event. But when i try to execute the js by firing the onclick only the <div id="fb-root"></div> gets updated, But no alert pops up.
function upload() {
function fbLoginStatus(response) {
if( response.status === 'connected' ) {
alert("Connected");
} else if( response.status === 'not_authorized') {
$('#overlay-shadow').fadeIn(500);
$('#overlay-container').fadeIn(650);
$('#scriptolution-soft-language.scriptolution-soft-box .content').html('<a href="javascript:void(0);" onclick="collapseAll();"
class="close-btn badge-language-close"></a><h3>Something is wrong !</h3><br/><h4>Our system got confused. Please try the "Download Cover"
option. Sorry.</h4>');
} else {
alert("Logged Out");
}
}
window.fbAsyncInit = function() {
FB.init({appId: '414212035337190', status: true, cookie: true, xfbml: true});
FB.getLoginStatus(fbLoginStatus);
FB.Event.subscribe('auth.statusChange', fbLoginStatus);
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
}
Here is the complete snippet of code that I am using. I have read through all the documentation and still not able to figure out this. I am running the code locally on visual studio 2010 and chrome browser. I have set my site url, canvas url and secure canvas url as localhost. I have my app domain empty. I am guessing that I am doing something wrong and I cannot figure out. Please help me
<html>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '129307260602861',
status : true,
cookie : true,
xfbml : true,
oauth : true,
});
FB.Event.subscribe('auth.login', function(response) {
fblogin(); //first login time
});
FB.Event.subscribe('auth.authResponseChange', function(response) {
alert('The status of the session is: ' + response.status);});
FB.Event.subscribe('auth.logout', function(response) {
alert('logout');
});
};
(function() {
var e = document.createElement('script');
e.type = 'text/javascript';
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
} ());
function fblogin() {
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
//check extened permisions
var access_token = response.authResponse.accessToken;
var user_id = response.authResponse.userID;
// Do your business
alert('here');
}
else {
//user is not logged in
alert('here');
}
});
}
</script>
<fb:login-button autologoutlink='true' perms='email,user_birthday,status_update,publish_stream'></fb:login-button>
</body>
</html>
I'm trying to login on my website with Facebook JS API from my iPhone. The login works fine on computer as well as iPad.
Here's the login screen:
On iPhone however, I get to a screen which looks like this:
When I close the Facebook screen with the "Back to previous page" message and reload the login page, I'm logged in successfully. It looks like the problem is, that iPhone is unable to close the login pop-up screen.
Here's my JavaScript code:
<div id="fb-root"></div>
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({
appId : '', // the app id
status : true,
cookie : true,
xfbml : true
});
FB.getLoginStatus(function(response) {
if (response.status == "connected") {
// do something
}
});
FB.Event.subscribe("auth.login", function(response) {
if (response.status == "connected") {
// do something
}
});
};
function facebookRedirectLogin(redirect) {
// do something
}
function logout() {
FB.logout(function(response) {
// do something
});
}
(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>
<div class="fb-login-button" style="margin-bottom: 20px;">Forbind med Facebook</div>
How can I fix this problem?
Checkout this URL,
please do the settings as mentioned in the above URL, this code is working in mobile devices.
<html>
<head>
<title>My Facebook Login Page</title>
</head>
<body>
<div id="fb-root"></div>
<div id="login">
<p><button onClick="loginUser();">Login</button></p>
</div>
<div id="logout">
<p><button onClick="FB.logout();">Logout</button></p>
</div>
<script>
function loginUser() {
FB.login(function(response) { }, {scope:'email'});
}
</script>
<script>
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>
<script>
window.fbAsyncInit = function() {
FB.init({ appId: 'xxxxxxxxxxxx',
status: true,
cookie: true,
xfbml: true,
oauth: true});
FB.Event.subscribe('auth.authResponseChange', handleResponseChange);
};
</script>
<script>
function handleReponseChange(response) {
document.body.className = response.authResponse ? 'connected' : 'not_connected';
if (response.authResponse) {
alert(response);
}
}
</script>
</body>
I have the exact same problem. This may (or may not) be an open Facebook bug: https://developers.facebook.com/bugs/280811108698311