Facebook Graph API, First Name stays empty [duplicate] - javascript

This question already has answers here:
Facebook JS SDK's FB.api('/me') method doesn't return the fields I expect in Graph API v2.4+
(4 answers)
Closed 6 years ago.
I was debugging an older script and came to the part where it should query a some Data of a Facebook user and store it into a Database.
Some of the scopes like publish_stream have been deprecated and so i replace it with "publish_actions". At least there is something i couldn't figure out. I would like to query the first and last name of the user but this reponse stays empty, the only that works is the thumbnail and the user ID.
So here are the scopes (i know public_profile is not necessary but facebook recommends it).
//function handleFacebookAuth(callback) {
function handleFacebookAuth(callback) {
var permissions = '';
//noinspection JSUnresolvedVariable
if (window.extendedPerms) {
permissions = 'public_profile,email,publish_actions,user_likes,' + window.extendedPerms;
} else {
permissions = 'public_profile,email,publish_actions';
}
if (accessToken != null && userId != null) {
callback(accessToken, userId);
} else {
FB.login(function (response) {
if (response.authResponse) {
userId = response.authResponse.userID;
accessToken = response.authResponse.accessToken;
callback(accessToken, userId);
} else {
$("#white-wall").hide();
}
}, {scope: permissions});
}
return false;
}
And here the query to the Data
function sendData(moves, seconds) {
FB.api('/me', function (response) {
var data = {
access_token: accessToken,
flag: 'data',
fbuid: response.id,
moves: moves,
seconds: seconds,
fname: response.first_name,
lname: response.last_name,
email: response.email,
gender: response.gender
};
userId = response.id;
$.ajax({
url: "ajax.php",
data: data, dataType: 'html', method: "post",
error: function (data) {
alert(data.responseText);
},
success: function (data) {
console.log(data);
//$( "#gameresults" ).html( data);
$('#gameresults').html(data);
$("#triggerbtn").fancybox({
'width': 480,
'height': 550,
'autoSize': false,
'overlayShow': false,
'scrolling': 'no'
});
$("#triggerbtn").trigger('click');
//window.top.location.href = data;
}
});
});
}
I hope that maybe someone see a mistake in it, i really can't figure out what is wrong with it, maybe the issue might be somewhere else and it would be great to hear that my code above is okay.

Okay thanks WizKid's hint the solution was pretty simple
I added to /me
FB.api('/me?fields=id,first_name,last_name,email,gender', function (response) {
That was all..

Related

using ajax with javascript to put in database

I'm trying to put the infos into my database, for that, this code is in the connexion.jsp which is a page that ask to log with facebook.
the code is supposed to be called into the Controller which is a file in java, and go into the databse.
So my problem is the fact that the code $.ajax doesn't seems to work. It doesn't give a success or error window.alert with or without function(){}.
I might have missed some information about ajax, but i can't find more info about my error.
function fbLogin() {
FB.login(function (response) {
if (response.authResponse) {
// Get and display the user profile data
getFbUserData();
$.ajax({
method: 'post',
url: '/hello/facebookconnection',
first_name: response.first_name,
last_name: response.last_name,
email: response.email,
success:
//success: function(){
window.alert('Sent User data!')//;}
,
error:
window.alert('Error in sending ajax data')
});
else {
document.getElementById('status').innerHTML = 'User cancelled';
}
}, {scope: 'email'});
}
function fbLogin() {
FB.login(function (response) {
if (response.authResponse) {
// Get and display the user profile data
getFbUserData();
$.ajax({
method: 'post',
url: '/hello/facebookconnection',
first_name: response.first_name,
last_name: response.last_name,
email: response.email,
success:
//success: function(){
window.alert('Sent User data!')//;}
,
error:
window.alert('Error in sending ajax data')
});
} else {
document.getElementById('status').innerHTML = 'User cancelled';
}
}, {scope: 'email'});
}
You have a syntax error in front of your else.

How to save a variable to the server using jQuery

I am implementing a video conference room and I have a variable (room_status) which holds the status of the room (0 = close & 1 = open). Now this variable is only accessible my the client who clicks open-room.
I need to save the room_status variable to the server so that it can be accessed on other client's side. Here is a piece of my code:
var room_status = 0; //room closed
$('#open-room').click(function () {
// http://www.rtcmulticonnection.org/docs/open/
$.ajax({
type: 'GET',
url: "../invite",
data: {
videoconference_id: $('#meetingID').val(),
invitee_id: 1111,
status: "Accepted"
},
success: function() {
alert("success!");
},
error: function() {
alert("fail");
}
});
//room_status = 1; //room opened
rmc.open();
rmc.streams.mute({video : true});
document.getElementById("on-off-video").style.color= 'red';
});
$('#join-room').click(function () {
if(room_status) {
// http://www.rtcmulticonnection.org/docs/connect/
rmc.connect();
rmc.streams.mute({video: true});
document.getElementById("on-off-video").style.color= 'red';
} else {
console.log("Waiting for meeting organizer");
}
});
Ajax is your friend.
Here is an example from a prject of mine with jquery ui :
function prepare_ajax_button(l){
$("#button").button().click(function(event,ui){
$.ajax({type: "GET",data: {"arg1":l},url: "update_variable.php",success: function(data){
alert("Success ?!");
},error: function(data){alert("Problem ?!");}});
});
}
The page "update_variable.php" can for instance write the variable in a text file, mysql...

jQuery AJAX: Update [LastVisitDate] Field on POST?

I have the below Login JavaScript for my MVC4 Application. I am attempting to add a value with my POST data to update the [LastVisitDate] each time a user logs in. However, whenever I login with my credentials, the value is still shown as 4/18/2014 10:04:47 AM. I have verified my cache has been cleared and am at a loss as to what I may be doing wrong.
Anyone have some thoughts on the matter?
function login()
{
var userName = $("#username").val();
var password = $("#password").val();
var rememberme = $("#rememberMe").is(':checked');
// NEWLY ADDED
var datestamp = Date.now();
var data =
{
Email: userName,
Password: password,
RememberMe: rememberme,
// NEWLY ADDED
LastVisitDate: datestamp
};
$.ajax(
{
url: "/Account/Login",
type: "POST",
data: data,
cache: false,
async: true,
success: function (data) {
$("#loginAlert").remove();
if (data.returnUrl != undefined) {
window.location.href(data.returnUrl);
}
else {
window.location.reload();
}
},
error: function (result) {
if ($("loginAlert").length() == 0) {
var errorMsg = 'There was an error.';
$("#navBar").after(errorMsg);
}
}
});
}
function EnterKeyPressed () {
if (event.keyCode == 13) {
login();
}
}
function closeAlert() {
$("#loginAlert").alert("close");
}
You have just posted the Ajax code and there is no clear information on what is going on in the background.
But based on your question I am assuming you are not returning the last logged in date. If its a SQL query then you need to perform a Order by date DESC. See if it helps :)

linkedin logout function(javascript API) is not working in some conditions

In my website, I have provided a facility to login via linkedin. I have used javascript API for that.
I have written below code for login.
function onLinkedInAuth() {
var isLoggedIn = document.getElementById('<%=hdnIsLoggedin.ClientID %>').value;
// Check for the session on the site
if (isLoggedIn == false || isLoggedIn == 'false') {
IN.API.Profile("me")
.fields("id", "firstName", "lastName", "industry", "emailAddress")
.result(function (me) {
//debugger;
var id = me.values[0].id;
var fname = me.values[0].firstName;
var lname = me.values[0].lastName;
var industry = me.values[0].industry;
var email = me.values[0].emailAddress;
// AJAX call to register/login this user
jQuery.ajax({
type: "POST",
url: "UserRegisterAsSeeker.aspx/LinkedinLoginOrRegister",
data: "{id:'" + id + "',fname:'" + fname + "',lname:'" + lname + "',email:'" + email + "'}",
contentType: "application/json; Characterset=utf-8",
dataType: "json",
async: true,
success: function (data) {
closeLoginWindow();
__doPostBack('<%=lnkRefreshPage.UniqueID%>', '');
},
error: function (request, status, error) {
alert('Unable to process the request at this moment! Please try again later.');
},
complete: function () {
}
});
});
}
}
Above code works fine.
And for logout i have used below function provided by linkedin
function logout() {
IN.User.logout(function () {
window.location.href = '/logout.aspx';
});
}
Problem is in logout. When we login to the site and immediately logout, it works fine but when we leave the site ideal for some time it does not logout from linkedin. We have to click 3-4 times then it works.
I don't know why it's happening. Please help if you can.

Fb.api post to user wall only on login

I would like to use fb.api to post on logged user, but just once. If I put this
var params = {};
params['message'] = 'gegeegeggegall! Check out www.facebook.com/trashcandyrock for more info.';
params['name'] = 'gegeggeeg - gegegege';
params['description'] = 'Check out Tegegegeg! Win merch by playing and reccomending to your friends.';
params['link'] = 'http://www.bblblba.com';
params['picture'] = 'http://summer-mourning.zoocha.com/uploads/thumb.png';
params['caption'] = 'Tgegegegeeg';
FB.api('/me/feed', 'post', params, function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Published to stream - you might want to delete it now!');
}
});
It posts to users wall everytime he refreshes the site?
What to do?
What is triggering the FB.api call? If it's just code within a tag then it's going to run as soon as the browser gets to that point.
You could possibly store some sort of cookie value or something after the FB.api call then check it on page load, but that seems like more work than is probably needed.
Do you want him to post it only once, ever?
If so, you're going to need to create a "state". In order to do this, you could do it client sided (with cookies), or server sided (with a database).
Create a boolean variable named "posted", and store it in a cookie or in a database (since you're using javascript, it's probably easier to use a cookie).
var posted=getCookie("posted");
if(!posted)
{
//call the FB.api();
setCookie("posted", true, duration);
}
Definition of setCookie and getCookie: http://www.w3schools.com/JS/js_cookies.asp
You could run a FQL query and check to see if the message has already been posted by querying the stream table with your app id. Something like:
<!DOCTYPE html>
<html>
<body>
<div id="fb-root"></div>
Post To Wall
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({ appId : '**yourAppID**', status : true, cookie : true, xfbml : true });
function postToWall() {
FB.login(function(response) {
if (response.session) {
FB.api(
{
method: 'fql.query',
query: 'SELECT post_id, message from stream where app_id = **yourAppID** and source_id = me()'
},
function(response) {
if(response.length == 0){
FB.ui(
{
method: 'feed',
name: 'Facebook Dialogs',
link: 'https://developers.facebook.com/docs/reference/dialogs/',
picture: 'http://fbrell.com/f8.jpg',
caption: 'Reference Documentation',
description: 'Dialogs provide a simple, consistent interface for applications to interface with users.',
message: 'Facebook Dialogs are easy!'
},
function(response) {
if (response && response.post_id) {
alert('Post was published.');
} else {
alert('Post was not published.');
}
}
);
}
else {
alert('User already posted this message');
}
}
);
}
} , {perms:''});
}
</script>
</body>
</html>

Categories

Resources