I'm playing around with the Facebook API in Javascript to try and pull posts from Facebook. I copied code from this page in the documentation. The function will access the page given and actually produce a response. But, response.length and response[i] are returning as "undefined" thus making it impossible for the loop to work. Why is this happening?
<button onclick="ShowMyPosts()">Show posts</button>
<script language="javascript" type="text/javascript">
function ShowMyPosts() {
FB.api('/TheWalkingDeadAMC/posts', { limit: 3 }, function(response) {
console.log(response)
console.log(response.length)
for (var i=0, l=response.length; i<l; i++) {
var post = response[i];
console.log(post)
if (post.message) {
console.log('Message: ' + post.message);
} else if (post.attachment && post.attachment.name) {
console.log('Attachment: ' + post.attachment.name);
}
}
}
)
console.log("successfully ran function")
};
</script>
How I get an access token. Is this incorrect?
FB.login(function(response) {
if (response.authResponse) {
var access_token = FB.getAuthResponse()['accessToken'];
console.log('Access Token = '+ access_token);
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
});
} else {
console.log('User cancelled login or did not fully authorize.');
}{scope: 'read_stream'}
});
When you query the Graph API - most results will be inside data key...
Using Graph API Explorer you can test your call and see what is the result without having to write a single line of code.
This is a direct link to your Graph API call test. as you can see data holds the posts.
So, you need to loop through response.data and not response.
The code should look like this:
function ShowMyPosts() {
FB.api('/TheWalkingDeadAMC/posts', { limit: 3 }, function(response) {
console.log(response.data);
console.log(response.data.length)
for (var i=0, l=response.data.length; i<l; i++) {
var post = response.data[i];
console.log(post)
if (post.message) {
console.log('Message: ' + post.message);
} else if (post.attachment && post.attachment.name) {
console.log('Attachment: ' + post.attachment.name);
}
}
}
I think the issue was that my FB.login was incorrect. This is the correct code below:
FB.login(
function(response) {
if (response.authResponse) {
var access_token = FB.getAuthResponse()['accessToken'];
console.log('Access Token = '+ access_token);
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
});
} else {
console.log('User cancelled login or did not fully authorize.');
}},
{scope: 'read_stream'}
);
Related
After successfully log in, i try to get a few fields from the user.
All of them are undefined other than the name and ID. The pop up indeed ask those permission which I granted.
Read all posts here and non offered a solution that work other than using tokens(?) which I am not sure how, and never see in FB examples.
FB.login(
function(response) {
if (response.status === "connected") {
console.log("connected");
console.log("Access Token: " + response.authResponse.accessToken);
testAPI();
} else {
console.log("not connected");
}
},
{ scope: "email,user_age_range,user_friends" }
);
function testAPI() {
console.log("Welcome! Fetching your information.... ");
FB.api("/me", function(response) {
console.log("name: " + response.name);
console.log("email: " + response.email);
console.log("id: " + response.id);
console.log("friends: " + response.user_friends);
console.log("age: " + response.user_age_range);
console.log("end");
});
}
If I print response i get an error :
Uncaught ReferenceError: respond is not defined
To anyone who wonder, first, the way to read it is :
FB.api('/me', {fields: 'name,email'}, (response) => {
console.log('name: ' + response.name);
console.log('email: ' + response.email);
});
Second, a few points to notice:
Remove your app on your facebook profiles (under Apps) otherwise every time you test, FB will automatically grant access even if you wish to add more permissions.
Remove cache from your browser every new test because FB will keep the previous state and changes will not take effect.(sometimes, even updated deployments will not)
You should deploy your website, with me - local host is not working with FB because they require https.
Testing Facebook is a little bit hassle.
i'm looking on what cases are these events is firing, i have implement it on these code
jQuery(document).ready(function() {
var chatChannel;
var chatClient;
var username;
var $input = $('#chat-input');
$.post("/tokens", function(data) {
username = data.username;
chatClient = new Twilio.Chat.Client(data.token);
chatClient.getSubscribedChannels().then(createOrJoinGeneralChannel);
});
function createOrJoinGeneralChannel() {
// Get the general chat channel, which is where all the messages are
// sent in this simple application
// print('Attempting to join "general" chat channel...');
var promise = chatClient.getChannelByUniqueName("#{params[:chat_channel]}");
promise.then(function(channel) {
chatChannel = channel;
console.log("#{params[:chat_channel]} is exist");
console.log(chatChannel);
setupChannel();
return channel.getMembers();
// $input.removeClass('.hidden')
})
.then(function(members){
members.forEach(function(member){
console.log('member', member);
member.on('userInfoUpdated', function(){
console.log('userInfoUpdated', member);
})
})
})
.catch(function() {
// If it doesn't exist, let's create it
console.log("creating #{params[:chat_channel]} channel");
chatClient.createChannel({
uniqueName: "#{params[:chat_channel]}",
friendlyName: 'General Chat Channel'
}).then(function(channel) {
console.log("Created #{params[:chat_channel]} channel:");
console.log(channel);
chatChannel = channel;
setupChannel();
});
});
}
function setupChannel() {
chatChannel.join().then(function(channel) {
printMessage(username + ' joined the chat.');
chatChannel.on('typingStarted', showTypingStarted);
chatChannel.on('typingEnded', hideTypingStarted);
chatChannel.on('memberJoined', notifyMemberJoined);
chatChannel.on('memberLeft', notifyMemberLeft);
chatChannel.on('memberUpdated', updateMemberMessageReadStatus);
});
chatChannel.on('messageAdded', function(message) {
printMessage(message.author + ": " + message.body);
});
}
function updateMemberMessageReadStatus(member){
console.log('memberUpdated');
console.log('member.lastConsumedMessageIndex', member.lastConsumedMessageIndex);
console.log('member.lastConsumptionTimestamp', member.lastConsumptionTimestamp);
}
function leaveCurrentChannel() {
if (chatChannel) {
chatChannel.leave().then(function (leftChannel) {
console.log('left ' + leftChannel.friendlyName);
leftChannel.removeListener('messageAdded', function(message) {
printMessage(message.author + ": " + message.body);
});
leftChannel.removeListener('typingStarted', showTypingStarted);
leftChannel.removeListener('typingEnded', hideTypingStarted);
leftChannel.removeListener('memberJoined', notifyMemberJoined);
leftChannel.removeListener('memberLeft', notifyMemberLeft);
leftChannel.removeListener('memberUpdated', updateMemberMessageReadStatus);
});
}
}
function showTypingStarted(member) {
console.log('somebody is typing');
$('#is_typing').html(member.identity + ' is typing...');
}
function hideTypingStarted(member) {
$('#is_typing').html('');
}
function notifyMemberJoined(member) {
console.log('notifyMemberJoined');
printMessage(member.identity + ' joined the channel');
}
function notifyMemberLeft(member) {
console.log('notifyMemberLeft');
printMessage(member.identity + ' left the channel');
}
$input.on('keydown', function(e) {
if (e.keyCode == 13) {
chatChannel.sendMessage($input.val());
$input.val('');
} else {
//console.log('typing');
chatChannel.typing();
}
});
window.addEventListener("beforeunload", function (e) {
// var confirmationMessage = "\o/";
(e || window.event).returnValue = leaveCurrentChannel(); //Gecko + IE
return leaveCurrentChannel(); //Webkit, Safari, Chrome
});
});
and i've take alook to the console to see if my
console.log('userInfoUpdated', member);
or these guys
console.log('memberUpdated');
console.log('member.lastConsumedMessageIndex', member.lastConsumedMessageIndex);
console.log('member.lastConsumptionTimestamp', member.lastConsumptionTimestamp);
and they are never fired, during my test on the chat events, and i'm confused on how exactly i'm going to display how my users online or the status of a message is read or unread
so please enlighten me on the case, thank you
Twilio developer evangelist here.
According to the JS docs for the latest version of Twilio Chat, the event you need to listen for on members is just called 'updated'. So, listening for 'userInfoUpdated' won't work.
I would also recommend that within this code:
chatChannel.join().then(function(channel) {
//...
chatChannel.on('memberUpdated', updateMemberMessageReadStatus);
//...
})
you use the channel passed to the callback, rather than the original chatChannel object. Like this:
chatChannel.join().then(function(channel) {
//...
channel.on('memberUpdated', updateMemberMessageReadStatus);
//...
})
I don't know if this will fix the issue, but I can't think of anything else right now.
I am using Google plus API to get email id from viewers in my website.
Google reference:https://developers.google.com/+/web/signin/add-button
The problem is when i click signin button i getting error "TypeError: gapi.client.plus is undefined" in browser console.
How to solve it.
My code:
<script src="https://apis.google.com/js/client:plusone.js?onload=signinCallback" type="text/javascript"></script>
<span id="signinButton">
<span class="g-signin"
data-callback="signinCallback"
data-clientid="*****************.apps.googleusercontent.com"
data-cookiepolicy="single_host_origin"
data-scope="profile">
</span>
</span>
function signinCallback(authResult) {
gapi.client.load('plus', 'v1',function(){});
if (authResult['status']['signed_in']) {
alert("login success");
document.getElementById('signinButton').setAttribute('style',
'display: none');
var request = gapi.client.plus.people.get({
'userId' : 'me'
});
request.execute(function(resp) {
var email = '';
if(resp['emails'])
{
for(var i = 0; i < resp['emails'].length; i++)
{
if(resp['emails'][i]['type'] == 'account')
{
email = resp['emails'][i]['value'];
}
}
}
alert("email ="+email);
console.log('ID: ' + resp.id);
console.log('Display Name: ' + resp.displayName);
console.log('Image URL: ' + resp.image.url);
console.log('Profile URL: ' + resp.url);
});
} else {
alert("login unsuccessful");
console.log('Sign-in state: ' + authResult['error']);
}
}
I had this problem,
I believe the problem is here
gapi.client.load('plus', 'v1',function(){});
The third parameter is empty, which Google declares as optional, but it tends to error as undefined because it's not being used or reached by the functions that are trying to use it.
Instead, you can try to nest the functions that need the gapi.client within that third parameter, or reference an external function there.
Here is what I did:
Google signin callback - get name and email
I belive the issue could be scope property in the params json passed as parameter for signIn API.
Scope parameter should contain below urls
"https://www.googleapis.com/auth/plus.login"
"https://www.googleapis.com/auth/plus.me"
and may be /userinfo.email, /userinfo.profile
I have a django project which is intended for a facebook application. In the project, the invite friends module runs fine in localhost!
But while it is loaded in facebook application, the javascript responsible for displaying the friends list doesn't work. Although the libraries are properly loaded.
I don't know why it is so. May be some iframe problem.
Here is the javascript code
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({appId: '460948667348013', cookie: true});
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
FB.api('/me', function(response) {
// alert('Your name is ' + response.name);
console.log('Your name is ' + response.name);
init();
});
} else if (response.status === 'not_authorized') {
alert('the user is logged in to Facebook, but has not authenticated your app');
} else {
alert('the user is not logged in to Facebook.');
}
});
}
function init() {
FB.api('/me', function(response) {
$("#username").html("<img src='https://graph.facebook.com/" + response.id + "/picture'/><div>" + response.name + "</div>");
$("#jfmfs-container").jfmfs({
max_selected: 15,
max_selected_message: "{0} of {1} selected",
friend_fields: "id,name,last_name",
pre_selected_friends: [1014025367],
exclude_friends: [1211122344, 610526078],
sorter: function(a, b) {
var x = a.last_name.toLowerCase();
var y = b.last_name.toLowerCase();
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
});
$("#jfmfs-container").bind("jfmfs.friendload.finished", function() {
window.console && console.log("finished loading!");
});
$("#jfmfs-container").bind("jfmfs.selection.changed", function(e, data) {
window.console && console.log("changed", data);
});
$("#logged-out-status").hide();
$("#show-friends").show();
});
}
$("#show-friends").live("click", function() {
var friendSelector = $("#jfmfs-container").data('jfmfs');
$("#selected-friends").html(friendSelector.getSelectedIds().join(', '));
});
function sendRequest() {
var friendSelector = $("#jfmfs-container").data('jfmfs');
var sendUIDs = friendSelector.getSelectedIds().join(', ');
// Use FB.ui to send the Request(s)
FB.ui({method: 'apprequests',
to: sendUIDs,
title: 'My Great Invite',
message: 'Check out this Awesome App!',
}, callback);
}
function callback(response) {
// alert('callback called');
var friendSelector = $("#jfmfs-container").data('jfmfs');
var sendUIDs = friendSelector.getSelectedIds().join(',');
var uids = sendUIDs.split(',');
var query = '';
for(i=0;i<uids.length;i++){
if(i==0){
query = query + 'to[' + i + ']=' + uids[i];
}
else{
query = query + '&to[' + i + ']=' + uids[i];
}
}
console.log(query);
if(response){
// alert('successful');
window.location.assign("/?"+ query)
}
else{
alert('failure');
}
}
</script>
Please help ! I am stuck with this problem.
The issue may be SSL issues.
Facebook has made many changes in few months ago.
Also you need to keep update with Facebook developer blog.
So I am going to try to explain few things I suspected.
App on Facebook
Your Canvas Page should be https://apps.facebook.com/yourchoosenname
1a. Your Canvas URL should be https://yoursite.com/yourapplication/
Website
http://yoursite.com/
Page Tab
Your Secure Canvas should be https://yoursite.com/yourapplication/
Your Page Tab URL should be https://yoursite.com/yourapplication/
Your Secure Page Tab URL should be https://yoursite.com/yourapplication/
In this case you will need SSL Certificate for site so You can find reliable yet cheap digital certificate from Here .
This mandatory for any Application to work on facebook.
Hope this will help you and others
I'm using the Facebook JavaScript API and have gone over their documatation and cannot find the answer to the following question.
After a user has granted your application specific permissions (in this case read_stream), how do you obtain that particular data? To be more specific I am using the following as part of my login process:
function login(){
alert("[fbCommon]" + ' > login');
FB.login(function(response) {
if (response.authResponse) {
//console.log('Welcome! Fetching your information.... ');
alert("[fbCommon]" + ' > login > ' + 'Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
//console.log('Good to see you, ' + response.name + '.');
alert("[fbCommon]" + ' > login > ' + 'Good to see you, ' + response.name + '.');
});
} else {
alert("[fbCommon]" + ' > login > ' + 'User cancelled login or did not fully authorize.');
//console.log('User cancelled login or did not fully authorize.');
}
}, {scope: 'read_stream'});
}
Thanks for your help.
If all you want is their stream/feed data, change the
FB.api('/me', function(response) {...})
to
FB.api('/me/feed', function(response) {...})
You can use the trusty Graph Explorer to check this