Append values automatically after facebook login is correct - javascript

I'm working on a cordova project and i'm using facebook login as one of the user authentication. The login works correctly but the issue is i have to press a button of an id getinfo before the values from facebook appear. But what i want to do is when the login is right the values should be appended automatically to the divs.
$(document).ready(function () {
$("#login").on('click', function (event) {
// Defaults to sessionStorage for storing the Facebook token
openFB.init({ appId: '000000000000000' });
// Uncomment the line below to store the Facebook token in localStorage instead of sessionStorage
// openFB.init({appId: 'YOUR_FB_APP_ID', tokenStore: window.localStorage});
openFB.login(
function (data) {
if (data.status === 'connected') {
$id = $("#id").append(data.id)
$name = $("#name").append(data.name)
$gender = $("#gender").append(data.gender)
$email = $("#email").append(data.email)
} else {
alert('Facebook login failed: ' + data.error);
}
});
});
});
how do i make my script work without using this below function
$(document).ready(function () {
$("#getinfo").on('click', function (event) {
openFB.api({
path: '/me',
success: function (data) {
console.log(JSON.stringify(data));
$id = $("#id").append(data.id)
$name = $("#name").append(data.name)
$gender = $("#gender").append(data.gender)
$email = $("#email").append(data.email)
document.getElementById("userPic").src = 'http://graph.facebook.com/' + data.id + '/picture?type=small';
},
error: errorHandler
});
});
});

Try this login function:
openFB.login(
function (data) {
if (data.status === 'connected') {
openFB.api({
path: '/me',
success: function (data) {
console.log(JSON.stringify(data));
$id = $("#id").append(data.id)
$name = $("#name").append(data.name)
$gender = $("#gender").append(data.gender)
$email = $("#email").append(data.email)
document.getElementById("userPic").src = 'http://graph.facebook.com/' + data.id + '/picture?type=small';
},
error: errorHandler
});
} else {
alert('Facebook login failed: ' + data.error);
}
});
});

Related

how to save javascript variable to my sql by using spring boot controller?

I need to store email_id to my sql using spring boot. How do I send this variable to controller without using submit-form action?
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', {
locale: 'en_US',
fields: 'name, email'
},
function(response) {
var email_id = response.email;
// }
//FB.api('/me', function(response)
// {
console.log('Successful login for: ' + 'thats it');
document.getElementById('status').innerHTML =
'Thanks for logging , ' + email_id + '!';
});
You can do something like the following.
var data = new FormData();
data.append('key', 'value');
function yourAjaxFunction() {
var ajaxCall = new XMLHttpRequest();
ajaxCall.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log("Printing the response here");
console.log(this);
}
};
ajaxCall.open("GET", "Your full url here", true);
ajaxCall.send(data);
}

conversationId - Value can't be NULL

In a Word-addin I'm am trying to fetch data from AAD with the help of ADAL and microsoft.graph. Here is the code:
from app.js
var app = (function () {
"use strict";
window.config = {
instance: 'https://login.microsoftonline.com/',
tenant: '<TENANT>',
clientId: '<CLIENTID>',
redirectUri: '<THE-APP-ADDRESS>',
postLogoutRedirectUri: window.location.origin,
endpoints: {
officeGraph: 'https://graph.microsoft.com',
},
callback: userSignedIn,
popUp: true,
cacheLocation: 'localStorage'
};
function signIn() {
authContext.login();
}
function userSignedIn(err, token) {
console.log('userSignedIn called');
// showWelcomeMessage();
if (!err) {
console.log("token: " + token);
showWelcomeMessage();
}
else {
console.error("error: " + err);
}
}
function showWelcomeMessage() {
var authContext = new AuthenticationContext(config);
var $userDisplay = $(".app-user");
var $signInButton = $(".app-login");
var $signOutButton = $(".app-logout");
// Check For & Handle Redirect From AAD After Login
var isCallback = authContext.isCallback(window.location.hash);
authContext.handleWindowCallback();
if (isCallback && !authContext.getLoginError()) {
window.location = authContext._getItem(authContext.CONSTANTS.STORAGE.LOGIN_REQUEST);
}
and main.js
function getDataFromSelection() {
var baseEndpoint = 'https://graph.microsoft.com';
var authContext = new AuthenticationContext(config);
Office.context.document.getSelectedDataAsync(Office.CoercionType.Text,
function (asyncResult) {
if (asyncResult.status === Office.AsyncResultStatus.Succeeded) {
authContext.acquireToken(baseEndpoint, function (error, token) {
if (error || !token) {
app.showNotification("Ingen token: ", "Du får logga in igen." + error); // + error
}
//var email = authContext._user.userName;
var url = "https://graph.microsoft.com/v1.0/" + config.tenant + "/me";
var html = "<ul>";
$.ajax({
beforeSend: function (request) {
request.setRequestHeader("Accept", "application/json");
},
type: "GET",
url: url,
dataType: "json",
headers: {
'Authorization': 'Bearer ' + token,
}
}).done(function (response) {
html += getPropertyHtml("Namn", response.displayName);
html += getPropertyHtml("Titel", response.jobTitle);
html += getPropertyHtml("Avdelning", response.officeLocation);
html += getPropertyHtml("Telefon jobb", response.businessPhones);
$("#results").html(html);
return postDataToContentControlers(response);
}).fail(function (response) {
// app.showNotification('Inloggningen slutade att fungera!', 'Du får logga ut och prova att logga in igen'); //response.responseText
}).always(function () {
console.log("AJAX is done!!")
})
});
} else {
app.showNotification('Error:', 'Något gick fel. Du får logga in igen.'); //result.error.message
}
}
);
}
On local wordklient it works but on Word online (Office 365 Pro Plus v.1609)
I get this when running the function getDataFromSelection();
Error from console
And right Before I login and i get confirmed and a token:
the parameter ConversationId is handled when you use microsoft-graph to GET mail-messages. Every mail has a conversationId... Why is it complaining about that regarding a GET against https://graph.microsoft.com/v1.0/me ?
Does anyone know how to get around this problem or Point me in the right direction? Thanks =)
EDIT: And I forgot to mention that this works online on Google Chrome but on Microsoft Edge The popup doesn't work at all regarding login Before even fetching any data. Only popup the addin again.

Facebook Javascript Ajax Authentication

I've got my Cordova app authenticating with Facebook although i'm trying retrieve some data and I get errors. Was wondering if my URL is incorrect. Can anyone spot a mistake in this?
Errors:
app: makeAPICalls: error:setting authenticatedUser to Yes and skip registration.{"readyState":0,"status":0,"statusText":"Error: SyntaxError: DOM Exception 12"}
function makeAPICallsFB(token) {
$.ajax(
{
//url: 'https://api.linkedin.com/v1/people/~?format=json',
url: 'https://graph.facebook.com/v2.6/me?fields=id,first_name,last_name,bio,email,work,friends,picture{url}',
//url: 'https://graph.facebook.com/v2.6/oauth/access_token',
beforeSend: function (xhr) {
try {
console.log("Authorization...");
xhr.setRequestHeader('authorization', 'Bearer ' + token);
console.log("Finished Auth...");
} catch(err) {
alert(err);
}
},
success: function (linkedInData) {
console.log("TEST....");
if (linkedInData != null) {
console.log("Success");
try {
console.log('app: makeAPICalls LinkedInData: ' + JSON.stringify(linkedInData) + " token: " + token);
console.log('name: ' + linkedInData.id);
vsetaService.saveLinkedInData(linkedInData, token);
checkUserStatus();
} catch(err) {
alert(err);
}
} else {
alert("Data is NULL!");
}
},
error: function (error) {
console.log("app: makeAPICalls: error:setting authenticatedUser to Yes and skip registration." + JSON.stringify(error));
//navigator.notification.confirm('Unable to connect to LinkedIn at this time.', confirmCallback, "VSETA - Think Material", ["Ok"]);
//Take user to Home if an error with LinkedIn + Temp assign access
authenticatedUser = 1;
homeScreen();
}
});
console.log("Finished!");
}
This is my FB Login
function oauth2_loginFaceBook() {
$.oauth2({
type: 'post',
auth_url: 'https://www.facebook.com/v2.6/dialog/oauth', // required
response_type: 'code', // required - "code"/"token"
token_url: 'https://www.facebook.com/v2.6/oauth/access_token', // required if response_type = 'code'
logout_url: '', // recommended if available
client_id: 'confidential', // required
client_secret: 'confidential', // required if response_type = 'code'
redirect_uri: 'http://localhost/callback', // required - some dummy url
other_params: { scope: 'public_profile', state: 'somethingrandom1234' } // optional params object for scope, state, display...
}, function (token, response) {
console.log('app: oauth2_login Success: ' + response.text);
// do something with token or response
makeAPICallsFB(token);
}, function (error, response) {
console.log('app: oauth2_login ERROR: ' + response.text + " AuthenticateUser anyways to allow access to App as of right now.");
//Take user to Home if an error with LinkedIn + Temp assign access
authenticatedUser = 1;
homeScreen();
});
}
Any help is appreciated!
EDIT: Linkedlin was done correctly and the code is almost the exact same!
function makeAPICalls(token) {
$.ajax(
{
//url: 'https://api.linkedin.com/v1/people/~?format=json',
url: 'https://api.linkedin.com/v1/people/~:(id,first-name,last-name,picture-urls::(original),headline,industry,num-connections,location,summary,specialties,site-standard-profile-request,api-standard-profile-request,public-profile-url,picture-url,positions:(id,title,summary,start-date,end-date,is-current,company:(id,name,type,size,industry,ticker)),educations:(id,school-name,field-of-study,start-date,end-date,degree,activities,notes))?format=json',
beforeSend: function (xhr) {
xhr.setRequestHeader('authorization', 'Bearer ' + token);
},
success: function (linkedInData) {
if (linkedInData != null) {
console.log('app: makeAPICalls LinkedInData: ' + JSON.stringify(linkedInData) + " token: " + token);
vsetaService.saveLinkedInData(linkedInData, token);
checkUserStatus();
}
},
error: function (error) {
console.log("app: makeAPICalls: error:setting authenticatedUser to Yes and skip registration." + JSON.stringify(error));
//navigator.notification.confirm('Unable to connect to LinkedIn at this time.', confirmCallback, "VSETA - Think Material", ["Ok"]);
//Take user to Home if an error with LinkedIn + Temp assign access
authenticatedUser = 1;
homeScreen();
}
});
}
I was thinking that it could be the URL. Any suggestions?
I think the problem is probably picture{url}
If you want the URL of their profile picture,
photoURL = "http://graph.facebook.com/" + response.id + "/picture";
EDIT
Alright then if that's not it I'll just tell you how I go about what you're trying to do.
Use facebook's SDK. It's way easier than using Ajax for this type of thing.
//1
//This initializes the SDK
FB.init({
appId : 'your app id goes here',
cookie : true, // enable cookies to allow the server to access
// the session
xfbml : true, // parse social plugins on this page
version : 'v2.6' // use graph api version 2.6
});
//2
//This loads the 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'));
//3
//This is the login button
<fb:login-button scope="public_profile,email" onlogin="facebookDoAThing();" data-max-rows="1" data-size="large" data-show-faces="true" data-auto-logout-link="true"></fb:login-button>
//4
//This function gets called by the button, then calls the next couple of functions
function facebookDoAThing() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
//5
//This checks that they authorized your app
function statusChangeCallback(response) {
if (response.status === 'connected') {
// logged into facebook and gave your app access to their account
getInfoAndSuch(response);
}
}
//6
//This is where you grab their info
function getInfoAndSuch(response){
authType = "facebook";
authId = response.authResponse.userID; //For the api call
// This is the SDK's api call syntax.
FB.api('/' + authId + '?fields=id,first_name,last_name,email,permissions',
function(response) {
firstName = response.first_name; //grabs first name
lastName = response.last_name; //grabs last name
email = response.email; //grabs email
photoURL = "http://graph.facebook.com/" + response.id + "/picture"; //Grabs photo url, probably an easier way to do this
});
//This removes your app from their account if you want that
FB.api("/me/permissions", "delete", function(response){});
That flow should be able to accomplish what you want.

How to logout only my FBapplication not my facebook account?

I am using facebook javascript sdk on my web application. I am using graph api to login my application. When I logged out from my application, my application is logged out and my facebook account is also logout.
How to logout only my application not my facebook account ?
Please help me if someone has found solution for this.
Code:
<script type="text/javascript">
var button;
var userInfo;
window.fbAsyncInit = function() {
FB.init({ appId: '########',
status: true,
cookie: true,
xfbml: true,
oauth: true});
showLoader(true);
function updateButton(response) {
button = document.getElementById('fb-auth');
userInfo = document.getElementById('user-info');
userdata = document.getElementById('user-data');
if (response.authResponse) {
//user is already logged in and connected
FB.api('/me', function(info) {
login(response, info);
});
button.onclick = function() {
FB.logout(function(response) {
logout(response);
});
};
} else {
//user is not connected to your app or logged out
button.innerHTML = 'Login';
button.onclick = function() {
showLoader(true);
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me', function(info) {
login(response, info);
});
} else {
//user cancelled login or did not grant authorization
showLoader(false);
}
}, {scope:'email,user_birthday,status_update,publish_stream,user_about_me'});
}
}
}
// run once with current status and whenever the status changes
FB.getLoginStatus(updateButton);
FB.Event.subscribe('auth.statusChange', updateButton);
};
(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 login(response, info){
if (response.authResponse) {
var accessToken = response.authResponse.accessToken;
userInfo.innerHTML = '<img src="https://graph.facebook.com/' + info.id + '/picture">' + info.name
+ "<br /> Your Access Token: " + accessToken;
button.innerHTML = 'Logout';
showLoader(false);
document.getElementById('other').style.display = "block";
}
}
function logout(response){
userInfo.innerHTML = "";
document.getElementById('debug').innerHTML = "";
document.getElementById('other').style.display = "none";
showLoader(false);
}
//stream publish method
function streamPublish(name, description, hrefTitle, hrefLink, userPrompt){
showLoader(true);
FB.ui(
{
method: 'stream.publish',
message: '',
attachment: {
name: name,
caption: '',
description: (description),
href: hrefLink
},
action_links: [
{ text: hrefTitle, href: hrefLink }
],
user_prompt_message: userPrompt
},
function(response) {
showLoader(false);
});
}
function showStream(){
FB.api('/me', function(response) {
//console.log(response.id);
streamPublish();
});
}
function share(){
showLoader(true);
var share = {
method: 'stream.share',
u: 'http://www.appovative.com/'
};
FB.ui(share, function(response) {
showLoader(false);
console.log(response);
});
}
function setStatus(){
showLoader(true);
status1 = document.getElementById('status').value;
FB.api(
{
method: 'status.set',
status: status1
},
function(response) {
if (response == 0){
alert('Your facebook status not updated. Give Status Update Permission.');
}
else{
alert('Your facebook status updated');
}
showLoader(false);
}
);
}
function showLoader(status){
if (status)
document.getElementById('loader').style.display = 'block';
else
document.getElementById('loader').style.display = 'none';
}
</script>
Their is function defined in FB object use this to destroy FB session ,
usage( via PHP)
$facebook->destroySession();
Or
FB API provides a logoutURL which will log the user out of their current Facebook account.
you can use it like this ,
$facebook = new Facebook($config);
$params = array('next' => 'www.yousite.com/test.php' );
$logoutURL = $facebook->getLogoutUrl($params);
***note
advisable to add below codes also (not in case if you dont want your user to log out of your site)
//remove PHPSESSID from browser
if ( isset( $_COOKIE[session_name()] ) )
setcookie( session_name(), '', time()-7000000, '/' );
//clear session from globals
$_SESSION = array();
With JS using a custom event
ref : (FB.logout() called without an access token. javascript sdk)
function fbLogoutUser() {
FB.getLoginStatus(function(response) {
if (response && response.status === 'connected') {
FB.logout(function(response) {
document.location.reload();
});
}
});
}

Page getting redirected before ajax completion

i use ajax to create a session and to redirect the page when the user clicks on a button like this .. im using this in the facebook api(using the api to create a session with the user.id)
FB.login(function(response) {
if (response.session) {
FB.api('/me', function(user) {
if (user!=null) {
var request = new XMLHttpRequest();
if(document.getElementById("ans2").value==""){
document.getElementById("belowbutton2").innerHTML ="Don't leave it blank!!";
}
else{
var request2 = new XMLHttpRequest();
request.onreadystatechange=function(){
if(request.readyState==4 && request.status==200){
document.getElementById("debugger").innerHTML = request.responseText;
window.location = "weekques/weekques.php";
}
}
var uid = user.id;
alert(uid);
var jqXHR = ($.ajax)({url:"sessions.php?uid="+uid,
async:false,
cache: false,
timeout: 30000,
error:function(){
window.location = "http://www.xyz.com";
},
success:function(){
request.open("GET", "weekques/answer.php?ans="+document.getElementById("ans2").value, true); //+"&qid="+qidjs
request.send();
}
});
}
}
});
}
});
but the problem is that the window is redirecting before the session is created ..
heres the
sessions.php file
<?php
session_start();
require_once("connection.php");
$user=mysql_query("SELECT * from `thebirbals`.`FBusers` where uid='$uid';");
$row_count=mysql_num_rows($result);
$_SESSION['uid']=$_GET["uid"];
$uid = $_SESSION['uid'] ;
if($row_count==1){
$_SESSION['name'] = $check["name"];
$_SESSION['profile_link'] = $check["profile_link"];
$_SESSION['dp'] = $check["dp"];
}
else{
require_once('facebook/src/facebook.php');
$facebook = new Facebook(array(
'appId' => '1550598824560526',
'secret' => '4cf28242b5abfa26be8fd3e2074e5724',
'cookie' => false
));
$fql = "SELECT first_name,profile_url,pic_small from user where uid=$uid";
$response = $facebook->api(array(
'method' => 'fql.query',
'query' =>$fql,
));
foreach($response as $val)
{
$_SESSION['name']=$val["first_name"];
$_SESSION['dp']=$val["pic_small"];
$_SESSION['profile_link']= $val["profile_url"];
$name = $val["first_name"];
$profile_link = $val["profile_url"];
$dp = $val["pic_small"];
echo "done";
}
$insert=mysql_query("INSERT INTO `thebirbals`.`FBusers` ( `uid`, `name`, `profile_link`, `dp`) VALUES ('$uid', '$name', '$profile_link', '$dp');");
}
?>
i want to redirect after the sessions.php is finished running this does not happen
ty in advance for any help .. :)
I took a stab. Not sure if this will fix your issue entirely, but take it as a starting point:
FB.login(function (response) {
if (response.session) {
FB.api('/me', function (user) {
if (user != null) {
if (document.getElementById("ans2").value == "") {
document.getElementById("belowbutton2").innerHTML = "Don't leave it blank!!";
}
else {
var uid = user.id;
alert(uid);
$.ajax({ url: "sessions.php?uid=" + uid,
async: false,
cache: false,
timeout: 30000,
error: function () {
window.location = "http://www.xyz.com";
},
success: function () {
$.get("weekques/answer.php", $.param({ "ans": document.getElementById("ans2").value }), function (data) {
alert("Answer received");
document.getElementById("debugger").innerHTML = data;
window.location = "weekques/weekques.php";
});
}
});
}
}
});
}
});

Categories

Resources