Calling Ajax method using javascript function - javascript

I'm working with jQuery Mobile.
My Code for move to details div ::
Go To Details
Now, I want to authenticate user with Facebook.
So I have applied ::
Login with Faceook
Function Calling for Authentication
function userLogin() {
FB.login(
function(response) {
if (response.authResponse) {
alert('logged in');
FB.api('/me', function(response) {
alert("Welcome " + response.name);
});
} else {
alert('not logged in');
}
},
{ scope: "email" }
);
}
I'm getting valid user response after authentication.Now I want to navigate to that details div.
So, how can I implement that ajax code after successfully login ??
Any suggestion will be appreciated.
Thanks.

Instead of changing the href attribute directly, you should bind the onclick event to a function returning true.
Modify your a tag.
Go To Details
Modify your userLogin function:
function userLogin() {
FB.login(
function(response) {
if (response.authResponse) {
alert('logged in');
FB.api('/me', function(response) {
alert("Welcome " + response.name);
});
} else {
alert('not logged in');
}
},
{ scope: "email" }
);
return true;
}
It seems that FB.login is an asynchronized operation. If you want to redirect after the login action, try to modify the location.hash after login. Note that the return value has changed to false.
function userLogin() {
var hash = '#details';
FB.login(
function(response) {
if (response.authResponse) {
alert('logged in');
FB.api('/me', function(response) {
alert("Welcome " + response.name);
window.location.hash = hash;
});
} else {
alert('not logged in');
}
},
{ scope: "email" }
);
return false;
}

Use $.ajax() for making a call to the Facebook API to authenticate and in the callback function of the ajax function, call the click event of the details link.
Maybe something like this,
$.ajax({
url : 'https://graph.facebook.com/me'+whatever,
success : function(){
$('#details').click()
}
});
The success function will be called when the ajax call is successful.

Related

Facebook login callback returns name but not email address

I'm using Facebook login in the simplest way, and getting a call back response:
<div id="fb-root"></div>
<script async defer crossorigin="anonymous" src="https://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v6.0&appId=881911462250499&autoLogAppEvents=1"></script>
<script>
window.fbAsyncInit = function() {
FB.getLoginStatus(function(response) {
FB.api('/me', function (response) {
console.log(response);
});
});
}
</script>
I log the response to the console and receive the name and id, but not email address. How can I get the email as well? Upon researching it, it should get it by default, am I wrong?
According to the Fb docs, This is how you do it.
function statusChangeCallback(response) { // Called with the results from FB.getLoginStatus().
console.log('statusChangeCallback');
console.log(response); // The current login status of the person.
if (response.status === 'connected') { // Logged into your webpage and Facebook.
testAPI();
} else { // Not logged into your webpage or we are unable to tell.
document.getElementById('status').innerHTML = 'Please log ' +
'into this webpage.';
}
}
window.fbAsyncInit = function() {
FB.init({
appId : '{app-id}',
cookie : true, // Enable cookies to allow the server to access the session.
xfbml : true, // Parse social plugins on this webpage.
version : '{api-version}' // Use this Graph API version for this call.
});
FB.getLoginStatus(function(response) { // Called after the JS SDK has been initialized.
statusChangeCallback(response); // Returns the login status.
});
};
function testAPI() { // Testing Graph API after login. See statusChangeCallback() for when this call is made.
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 + '!';
});
}
You can check login status in this way.
function checkLoginState() { // Called when a person is finished with the Login Button.
FB.getLoginStatus(function(response) { // See the onlogin handler
statusChangeCallback(response);
});
}
By default, fb allows only basic permissions. What you require is additional permission, hence you have to request it this way.
FB.login(function(response) {
// handle the response
}, {scope: 'email,user_likes'});
You can read more about it here. Hope it helps :)
Ok got it, I was confused and it shoudl be here:
FB.api('/me', { locale: 'tr_TR', fields: 'email,name' }, function (response) {

Email not able to retrieve from facebook javascript SDK [duplicate]

I am using JavaScript API to create my app for Facebook. The problem is, it's returning
email = undefined.
I don't know why? And if I use Facebook login/logout button on my app then the alert shows correct email id of the user but I don't want to do that.
What am I missing?
Here is my code:
<p><fb:login-button autologoutlink="true" perms="user_about_me,email"></fb:login-button></p>
<script>
window.fbAsyncInit = function () {
FB.init({ appId: '250180631699888', status: true, cookie: true,
xfbml: true
});
FB.getLoginStatus(function (response) {
if (response.session) {
greet();
}
});
};
(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 greet() {
FB.api('/me', function (response) {
alert('Welcome, ' + response.name + "!");
alert('Your email id is : '+ response.email);
});
}
</script>
// https://developers.facebook.com/docs/javascript/reference/FB.api/
// v2.4
FB.api('/me', { locale: 'en_US', fields: 'name, email' },
function(response) {
console.log(response.email);
}
);
here is example how i retrieve user name and e-mail:
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
$(function() {
FB.init({
appId : 'APP_ID',
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') {
getCurrentUserInfo(response)
} else {
FB.login(function(response) {
if (response.authResponse){
getCurrentUserInfo(response)
} else {
console.log('Auth cancelled.')
}
}, { scope: 'email' });
}
});
function getCurrentUserInfo() {
FB.api('/me', function(userInfo) {
console.log(userInfo.name + ': ' + userInfo.email);
});
}
});
</script>
According to the latest info on the facebook page you should use 'scope' instead of perms.
https://developers.facebook.com/docs/reference/javascript/FB.login/
If you visit
https://developers.facebook.com/tools/console/
and use the fb-api -> user-info example as a starting point, then logout and back in again, it should ask you for email perms and you can see your email being printed. It is done using response.email as you mention in your post.
<button id="fb-login">Login & Permissions</button>
<script>
document.getElementById('fb-login').onclick = function() {
var cb = function(response) {
Log.info('FB.login callback', response);
if (response.status === 'connected') {
Log.info('User logged in');
} else {
Log.info('User is logged out');
}
};
FB.login(cb, { scope: 'email' });
};
</script>
Use this to for extra permission
for more details visit :
https://www.fbrell.com/examples/
In this code i have get user data form facebook and store into my database using ajax
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me?fields=email,name,first_name,last_name', function(response)
{
FB.api(
"/"+response.id+"/picture?height=100",
function (responses) {
//console.log(responses.data.url)
response['profile_pic']=responses.data.url;
$.ajax({
type:"POST",
url:'<?php echo base_url(); ?>'+'home/facebook_get_signup',
data:response,
success:function(res)
{
if(res=='success')
{
window.location='<?php echo base_url(); ?>';
}
if(res=='exists')
{
window.location='<?php echo base_url(); ?>';
}
}
});
}
)
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
// handle the response
}, {scope: 'email,user_likes'});
There are a couple of things wrong with your solution. First of all you are using the old authentication scheme. You should use the new one described here :
https://developers.facebook.com/docs/reference/javascript/
You need to add the oauth:true to your init function, and make sure that your getLoginStatus looks for the new type of response.
When that is said you need to make sure you have the right permissions to see the users e-mail. You can see the required permissions here:
http://developers.facebook.com/docs/reference/api/user/
You get those by using the FB.login function as described by TommyBs in another answer.
Once you have those options you can use the FB.api function to get the e-mail.

Need to check if user selected only me to share [facebook api]

I am trying to figure out how can I get to know if a user shares a link to his feed selecting only me as an option. I want to know this because if the user shares my link to himself then the promotion of my website won't be possible.
<div id="fb-share">Share</div>
<div class="social-share-wrap"></div>
jQuery('#fb-share').on('click', function() {
checkLoginState();
});
function statusChangeCallback(response) {
console.log(response);
if (response.status === 'connected') {
shareUrl();
} else if (response.status === 'not_authorized') {
checkLoginState();
} else {
checkLoginState();
}
};
function checkLoginState() {
FB.login(function (response) {
console.log(response);
statusChangeCallback(response);
}, {scope: 'email'});
};
function shareUrl() {
FB.ui({
method: 'feed',
link: 'http://www.example.com',
}, function(response) {
if (response && response.post_id) {
FB.api('/me', function (response) {
jQuery.post('test.php',{name: response.name, email: response.email}).done(function(data) {
jQuery('.social-share-wrap').html(data);
jQuery.fancybox({
href: '#social-share',
centerOnScroll: true,
hideOnOverlayClick: false
});
return false;
});
});
} else {
console.log('cancelled by user');
}
});
};
In the above code what I'm doing is when a user clicks the share div the user gets the login popup and then the user gets the permission popup and then the share iframe appears now if the user shares successfully his info is posted to test.php and if the user cancels it gets logged in console. I did not find anything in the api where I can get to know if user selects custom and sets it to only me.
You can´t check the permission setting, it´s completely up to the user and there is no way to detect which one he selected. After all, you are not allowed to incentivize sharing according to the platform policy, so it´s not really relevant to know.

Facebook Login Button callback function

I got a Problem with the Facebook Login on my Website. The Code Below is my FB-Connect Code. The commented part of the code sign's me in to my Website. My Problem is when i "reactivate" this code it logs me in instandly everytime i visit the page. But i want to log the user in when he clicks the "Login with Facebook"-Button. When I clicks the facebook login button a Popup shows up and nothing happens..
Can i somehow call a JS function when i click the FB-Connect button?
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'xxxxxxxxxxxxxxxxxx', // App ID
status : true,
cookie : true,
xfbml : true,
oauth : true,
});
var login = false;
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
console.log('connected');
login=true;
var uid = response.authResponse.userID;
//this part of the code below redircts me to the part, where i login to my system.
/*var accessToken = response.authResponse.accessToken;
$.ajax({
type: 'POST',
url: '/?eID=login',
data: $(this).serialize(),
success: function(msg) {
alert("LOGIN");
$('#content').load('/live-session/tickets/');
}
});*/
}});
You need to use FB.login function on click on fb connect button and don't use FB.getLoginStatus
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.');
}
});
From Doc
FB.getLoginStatus allows you to determine if a user is logged in to
Facebook and has authenticated your app.
So, if you don't want to check whether user has logged in on page load, don't call this
When I clicks the facebook login button a Popup shows up and nothing happens..
If you had already authorized the app and authenticated, facebook wont ask you again for login and authorization

How to get action id to delete previously posted action on timeline

I am using following code to post actions on timeline
<script type="text/javascript">
function read()
{
FB.api('/me/app_namespace:read' +
'?article=http://example.com/test.php&access_token=','post',
function(response) {
var msg = 'Error occured';
if (!response || response.error) {
if (response.error) {
msg += "\n\nType: "+response.error.type+"\n\nMessage: "+response.error.message;
}
alert(msg);
}
else {
alert('Post was successful! Action ID: ' + response.id);
}
});
}
</script>
Now i want to use the following code to delete action but the problem is dont know how to save the "action id" from above code so that it can be used in following code.
<script type="text/javascript">
function deleteAction()
{
FB.api(
'/actionid',
'delete',
function(response) {
alert('action deleted')
});
}
</script>
Thanks!
It depends, are you looking to delete the action in a later session or current? In the current session itself, you can probably simply store it in a variable. For eg:
function read()
{
FB.api('/me/app_namespace:read' +
'?article=http://example.com/test.php&access_token=','post',
function(response) {
var msg = 'Error occured';
if (!response || response.error) {
if (response.error) {
msg += "\n\nType: "+response.error.type+"\n\nMessage: "+response.error.message;
}
alert(msg);
}
else {
alert('Post was successful! Action ID: ' + response.id);
var idToDeleteLater = response.id;
}
});
}
function deleteAction()
{
FB.api(
'/'+idToDeleteLater,
'delete',
function(response) {
alert('action deleted')
});
}
As you can see, that's pretty straightforward, all you've done is stored the actionID in a variable. You can potentially store multiple IDs in an array or something.
On the other hand, if you want to delete the actions in a later session (unlikely for a "read" action), then you need to store these action IDs in a database or something, and pull the action from there prior to deleting.

Categories

Resources