Persisting Facebook data into Mongodb (Node.js + Express + jade) - facebook

I am developing simple web app that asks for Facebook access token and retrieve 'post' data of logged-in user.
After clicking 'login', it calls FB.api to retrieve user posts and use innerHTML in javascript to update user-status:
<div id="fb-root"></div>
<div id="user-info"></div>
<div id="user-email"></div>
<div id="user-status" name="post"></div>
<button id="fb-auth">Login</button>
My goal is to persist these updated data into mongodb.
What i have tried is to force to submit the form when the post is retrieved and pass the data in 'name="post"', However, this makes the page refreshes again and also the value shows undefined.
Javascript:
FB.api('/me/posts', { limit: 100 }, function(response) {
var userStatus = document.getElementById('user-status');
for (var i=0, l=response.data.length; i<l; i++) {
var post = response.data[i];
if (post.message) {
userStatus.innerHTML = userStatus.innerHTML + ' ' + post.message ;
var form = document.createElement('form');
form.setAttribute('method', 'post');
form.style.display = 'hidden';
document.body.appendChild(form);
form.submit();
} else if (post.attachment && post.attachment.name) {
alert('Attachment: ' + post.attachment.name);
}
}
});
app.js(req.param('post') is undefined, thus mongodb injects undefined data):
app.post('/', function(req, res){
postProvider.save({
posts: req.param('post')
}, function(error, docs){
res.redirect('/')
});
});
Any advice will be greatly appreciated.
Thank you for your time.

To get form data you have to use:
req.body.post

Related

Form - new page on submit button

Last year i build a form for one of our costumers, when visitors submitted the form they
got a message on the same page. But now he asks me if it is possible to
make a succes page if the form is filled in correctly.
I can't make it work. It's a bit out of my league.
So i hope anyone of you can help me out!
$(document).ready(function() {
$("#ajax-contact-form").submit(function() {
$('#load').append('<center><img src="ajax-loader.gif" alt="Currently Loading" id="loading" /></center>');
var fem = $(this).serialize(),
note = $('#note');
$.ajax({
type: "POST",
url: "contact/contact2.php",
data: fem,
success: function(msg) {
if ( note.height() ) {
note.slideUp(500, function() { $(this).hide(); });
}
else note.hide();
$('#loading').fadeOut(300, function() {
$(this).remove();
// Message Sent? Show the 'Thank You' message and hide the form
result = (msg === 'OK') ? '<div class="success">Uw bericht is verzonden, we nemen z.s.m. contact met u op!</div>' : msg;
var i = setInterval(function() {
if ( !note.is(':visible') ) {
note.html(result).slideDown(500);
clearInterval(i);
}
}, 40);
}); // end loading image fadeOut
}
});
return false;
});
<form id="ajax-contact-form" target="_blank" method="post" action="javascript:alert('success!');" >
Instead of displaying the "success" message, redirect to a new page:
window.location = successPageUrl;
Just redirect to success page after ajax success.

Play SoundCloud links through Soundmanager2

I'm using the Soundmanager Mp3 Button on my site. However, I'd like to use the Soundcloud Api to stream tracks through Soundmanager instead of hosting MP3's. Basically, I'd like to stream a Soundcloud link through the Soundmanager button. Possible?
I've tried creating a jQuery loop (below) but still haven't had any luck.
<ol>
<li><a class="sm2_button" href="http://soundcloud.com/....">Track Title</a>
</li>
</ol>
and the jQuery
$("ol a").each(function()
{
var thisLink = $(this);
var track_url = this.href; // save href value of each link to 'track_url' i.e. soundcloud.com/...
this.href = this.href.replace(track_url, "#"); // replace href value with '#'
var consumer_key = 'My Consumer Key';
// now resolve the stream_url through Soundcloud's getJSON method
$.when($.getJSON('http://api.soundcloud.com/resolve?url=' + track_url + '&format=json&consumer_key=' + consumer_key + '&callback=?', function(track) {
url = track.stream_url + '?consumer_key=' + consumer_key;
})).done(function() {
// and place an 'onclick' on each link
$(thisLink).attr('onclick', "if (basicMP3Player.lastSound) { basicMP3Player.lastSound.stop(); } document.getElementById('mp3').type='audio/mpeg'; document.getElementById('mp3').href = '" + url + "'; basicMP3Player.handleClick({target: document.getElementById('mp3')});");
});
});
This was driving me nuts too. After a bunch of digging I was able to get it to work if I specified an mp3 mimetype in the link:
<ol>
<li><a type="audio/mp3" class="sm2_button" href="https://api.soundcloud.com/tracks/49349198/stream?client_id=YOUR_CLIENT_ID">Track Title</a></li>
</ol>
You could also try using the SoundCloud Javascript SDK, which'll take care of most of this for you.
SC.initialize({
client_id: "YOUR_CLIENT_ID",
redirect_uri: "http://example.com/callback.html",
});
SC.stream("/tracks/293", function(sound){
sound.play();
});
I tried this and thought I had it...anyone see anything?
<script src="http://connect.soundcloud.com/sdk.js"></script>
<script>
SC.initialize({
client_id: "My Consumer Key",
redirect_uri: "My Redirect",
});
SC.get("/users/MYUSERID/tracks", {limit: 1000}, function(tracks){
alert("Latest track: " + tracks[0].title);
});
$(".sm2_button").live("click", function(sound){
sound.play();
});
</script>
<script>
$(document).ready(function() {
$(".sm2_button").each(function()
{
var thisLink = $(this);
var track_url = this.href; // save href value of each link to 'track_url' i.e. soundcloud.com/...
this.href = this.href.replace(track_url, "#"); // replace href value with '#'
var consumer_key = 'My Consumer Key';
// now resolve the stream_url through Soundcloud's getJSON method
$.when($.getJSON('http://api.soundcloud.com/resolve?url=' + track_url + '&format=json&consumer_key=' + consumer_key + '&callback=?', function(track) {
url = track.stream_url + '?consumer_key=' + consumer_key;
})).done(function() {
// and place an 'onclick' on each link
$(thisLink).attr('onclick', "if (basicMP3Player.lastSound) { basicMP3Player.lastSound.stop(); } document.getElementById('mp3').type='audio/mpeg'; document.getElementById('mp3').href = '" + url + "'; basicMP3Player.handleClick({target: document.getElementById('mp3')});");
});
});
}); </script>

Facebook login not responding to FB.login response

I am working on a android phonegap application with facebook integration.
FB.login(function(response) function has a response handler it is being called when
user click on fb button, but its not getting into the function response
or alert('test') every time. it gets into this script only when i hit
around 5 or 6 times. wat i need is to fetch the access token the very first time i logged into facebook. i have gone through a lot of links regarding this but
cant find an exact solution for this...
FB login callback function not responding if user is already logged in facebook
Even this question seems to be same but i cant figure it out my solution.
this is the code am working :
<div id="data">Hello Facebooktesters, loading ...</div>
<button onclick="login()">Login</button>
<button onclick="me()">Me</button>
<button onclick="logout()">Logout</button>
<button onclick="Post()">facebookWallPost</button>
<script type="text/javascript">
document.addEventListener('deviceready', function() {
try {
alert('Device is ready! Make sure you set your app_id below this alert.');
FB.init({
appId : "xxxxxxxxxxxxxxx",
nativeInterface : CDV.FB,
useCachedDialogs : false
});
document.getElementById('data').innerHTML = "FB init executed";
} catch (e) {
alert(e);
}
}, false);
function me() {
FB.api('/me/friends', {
fields : 'id, name, picture'
}, function(response) {
if (response.error) {
alert(JSON.stringify(response.error));
} else {
var data = document.getElementById('data');
fdata = response.data;
console.log("fdata: " + fdata);
response.data.forEach(function(item) {
var d = document.createElement('div');
d.innerHTML = "<img src="+item.picture+"/>" + item.name;
data.appendChild(d);
});
}
var friends = response.data;
console.log(friends.length);
for ( var k = 0; k < friends.length && k < 200; k++) {
var friend = friends[k];
var index = 1;
friendIDs[k] = friend.id;
//friendsInfo[k] = friend;
}
console.log("friendId's: " + friendIDs);
});
}
function login() {
FB.login(function(response) {
alert('test');
if (response.authResponse) {
alert('logged in');
var access_token = FB.getAuthResponse()['accessToken'];
alert(access_token);
window.location = "test.html"
} else {
alert('not logged in');
}
}, {
scope : "email"
});
}
function logout() {
alert('test');
FB.logout(function(response) {
alert('logged out');
//window.location.reload();
});
}
function Post(ele) {
var domain = 'http://192.168.0.46:8082/';
console.log('Debug 1');
var params = {
method: 'feed',
name: 'test - test',
link: domain+'test/test/showproddetails.action?product.productId=1',
picture: 'http://www.careersolutions.com/test.png',
caption: 'test',
description: 'test'
};
console.log(params);
FB.ui(params, function(obj) { console.log(obj);});
}
</script>
Thank you,
raj
You are missing semicolon in this line :
window.location = "test.html"
This question was posted a while ago but I would like to point out something. FB.login function opens a popup dialog asking if the user would like to log in to your app using Facebook. It is generally recommended that it be run after clicking a button as most browsers would block popup dialogs when a page loads. If the user had previously authorized your app then the popup dialog redirects back to your app and closes the dialog box (assuming your app is a website).
If what you intended to do was to check whether a user is logged in to your app upon page load, then it's recommended that you instead use FB.getLoginStatus method like so
function checkLoginState() {
FB.getLoginStatus(function(response) {
// Check response.status to see if user is logged in
alert(response.status);
});
}
Refer to this extensive documentation on facebook

Facebook credit api problem

I am using facebook credits api and using its pay method, following is my code:
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({
'appId' : '<?php echo $app_id; ?>',
'session' : <?php echo json_encode($session); ?>, // don't refetch the session when PHP already has it
'status' : true, // check login status
'cookie' : true, // enable cookies to allow the server to access the session
'xfbml' : true // parse XFBML
});
// whenever the user logs in, we refresh the page
FB.Event.subscribe('auth.login', function() {
window.location.reload();
});
FB.Canvas.setAutoResize();
};
(function() {
FB_RequireFeatures(["CanvasUtil"], function() {
FB.CanvasClient.scrollTo(0, 0);
window.FB = null;
var e = document.createElement('script');
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
});
}());
</script>
<script type="text/javascript">
function placeOrder() {
var order_info = { "title":"Music Mood Points",
"description":"Get Music Mood Points to purchase avatars",
"price":"10",
"product_url":"abc"
};
// calling the API ...
var obj = {
method: 'pay',
order_info: order_info,
purchase_type: 'item'
};
FB.ui(obj, callback);
}
var callback = function(data) {
if (data['order_id']) {
writeback("Transaction Completed! </br></br>"
+ "Data returned from Facebook: </br>"
+ "<b>Order ID: </b>" + data['order_id'] + "</br>"
+ "<b>Status: </b>" + data['status']);
} else if (data['error_code']) {
writeback("Transaction Failed! </br></br>"
+ "Error message returned from Facebook:</br>"
+ data['error_message']);
} else {
writeback("Transaction failed!");
}
};
</script>
function writeback(str) {
$('.get_points').html(str);
}
</script>
And here is button to click:
<input type="button" onclick="placeOrder();" value="GET More POINTS NOW" />
So when I click the button , it says in a facebook popup: Your application is not responding correctly.
So is there some thing missing in code or some thing that need to specify from application settings. Do any one have any idea. Any little thing you can tell is appreciated.
thanks in advance
When you place an order Facebook is making an backend call to your server (to the path set in the application setting page (under credit section).
That error means your application is not replying correctly to that initial call (there are actually two that will take place)
See http://developers.facebook.com/docs/creditsapi/
for more including sample code for your backend.

Facebook: get list of pages that a user is admin of

I'm using the graph api.
I have a logged in user, and want to get back a list of page ids of all the pages that the user is an admin of.
Is there a way of doing this? The docs are pretty bad - and circular.
Its simple with Graph API. Steps:
Get the manage_pages permission from the user (extended permissions).
Call the Graph API - https://graph.facebook.com/me/accounts
You can test this procedure in the graph explorer -> Just click on 'Get Access Token' button-> under 'Extended permission' check 'manage_pages' & submit it. It will give you the admin-page-details JSON.
I solved it with some FQL:
FB.api({method: 'fql.multiquery',
access_token: <access_token>,
queries: {
query1: 'select page_id from page_admin where uid = ' + <uid>,
query2: 'select page_id, name, page_url from page where page_id in (select page_id from #query1)'
}
}, function(queries){
var pages = queries[1].fql_result_set;
}}
go to this address
https://developers.facebook.com/tools/explorer/431294226918345/?method=GET&path=me%2Faccounts%3Ftype%3Dpage`
Just click on get Access token and go to extended Permission
Check the manage_pages checkbox
and click Get Access Token
Then under FQL write this
me/accounts?type=page
Click on Submit . and you will get all page lists that logged in user admin
You can call FB.api(/me/accounts) if you don't want to use FQL.
'accounts' is a connection of the User object. See the documentation for this # http://developers.facebook.com/docs/reference/api/user
Of course, with Facebook, there's always a catch. Right now this method will return not only the pages the user is an admin of, but also what applications they have installed. I'm almost positive this is NOT the intended behavior - I seem to remember using this a few months ago and only getting a list of pages. The documentation makes no mention of applications in this list either.
This is an easy problem to solve though - Facebook returns the name, category, and id for each item on the list, and each application has a category of 'Application'. I'm simply making sure I only list items whose category is not 'Application'.
You ask for the permission with the JavaScript SDK on login
FB.login(function(){}, {perms:'manage_pages'});
and then once they log in you can retrieve the pages (and apps) as follow :
FB.api('/me/accounts', function(response){
console.log(response);
})
You can also use "pages_show_list" permission, if you want only the list of facebook pages the user is admin of.
The "manage_pages" permission will ask the user permission to manage his pages, which can be too intrusive depending on what you need it for.
Note that your solution returns Pages as well as Applications. If you strictly want Pages, you can use FQL Multiquery with a "Type not equals" clause like this:
{
"query1":"select page_id from page_admin where uid = me()",
"query2":"select page_id, name, page_url, type from page where type!='APPLICATION' AND page_id in (select page_id from #query1)"
}
Permission
$facebook->getLoginUrl( array( "scope" => "manage_pages" ) );
action
$accounts = $facebook->api('/me/accounts');
return $accounts;
<head>
<link rel="stylesheet" href="#Url.Content("~/Content/jquery.remodal.css")">
</head>
<body>
<script type="text/javascript" src="#Url.Content("~/Scripts/Home/jquery.remodal.js")"></script>
<div class="remodal" id="page-selector-remodal" data-remodal-id="pageselector">
<p>Please select a facebook page Share </p>
<div id="page-name-container">
<select id="page-name" class="form-control">
</select>
</div>
<a class="remodal-confirm" id="facebookPageSelectSubmit" href="#">OK</a>
<a class="remodal-cancel" id="remodal-cancel" href="#">CANCEL</a>
</div>
<div data-remodal-id="modal-status">
<p id="modal-status-content">
The Account you have selected does not have Email.
</p>
<br>
<a class="remodal-confirm" href="#">OK</a>
</div>
<script type="text/javascript>
(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'));
window.fbAsyncInit = function () {
FB.init({
appId: 'YOUR APP ID',
cookie: true, // enable cookies to allow the server to access
// the session
xfbml: true, // parse social plugins on this page
version: 'v2.2' // use version 2.1
});
};
var pageSelector = $('[data-remodal-id=pageselector]').remodal();
var modalstatus = $('[data-remodal-id=modal-status]').remodal();
function statusChangeCallback(response) {
if (response.status === 'connected') {
// Logged into your app and Facebook.
//testAPI();
} else if (response.status === 'not_authorized') {
// The person is logged into Facebook, but not your app.
$("#modal-status-content").empty().html(response.status);
modalstatus.open();
}
else {
$("#modal-status-content").empty().html(response.status);
modalstatus.open();
// The person is not logged into Facebook, so we're not sure if
// they are logged into this app or not.
document.getElementById('status').innerHTML = 'Please log ' +
'into Facebook.';
}
}
function FacebookHandler() {
FB.login(function (result) {
if (result != null && result.authResponse != null && result.authResponse != undefined) {
facebookPageData = result;
FB.api('/me/accounts', function (accountsResult) {
if (accountsResult != null && accountsResult.data.length != 0) {
//open the remodal here
pageSelector.open();
facebookAccountsData = accountsResult;
var data = accountsResult['data'];
if (data != null) {
for (var i = 0; i < data.length; i++) {
$("#page-name").append('<option value="' + data[i].id + '">' + data[i].name + '</option>');
}
}
unblockUI('body');
$("#flip-container, #feature-container, #branding-container, #intro-arrow-container, #share-container, #copyright-text-container").hide();
$("body").css("padding-right", "0");
}
else {
$("#modal-status-content").empty().html("The Account you have selected does not have any facebook page,<br />Post to Wall.");
modalstatus.open();
pageSelector.open();
unblockUI('body');
}
});
}
else {
$("#modal-status-content").empty().html("Unable to retrieve your details from facebook, try again after sometime.");
modalstatus.open();
unblockUI('body');
}
}, { scope: 'manage_pages, publish_stream' });
}
$("#facebookPageSelectSubmit").on("click", function () {
var facebookpageId = $("#page-name option:selected").val();
if (facebookpageId != null) {
FB.api('/' + facebookpageId, function (identity) {
if (identity != null) {
FB.api('/' + facebookpageId, { fields: 'access_token' }, function (resp) {
if (resp.access_token != null) {
//Get the "resp"(Data) here
}
else {
}
});
}
else {
}
});
}
else {
}
});
</script>
//Finally call the "FacebookHandler()" function on click
</body>
With the new GRAPH API v3 with Javascript use the 'tasks' field instead of 'perms' field.
//Example JS Call
FB.api('/me/accounts?fields=name,picture.type(square),access_token,tasks', function(response) {console.log(response)});
//Example Response
{
"name": "Engage",
"picture": {
"data": {
"height": 50,
"is_silhouette": false,
"url": "https://scontent.xx.fbcdn.net/v/t1.0-1/c1.0.50.50a/p50x50/430597_259746387431503_2144341304_n.jpg?_nc_cat=103&_nc_eui2=AeGVrU8Wxe7k5BMvRXOEAcUo9dMIxyeMP9POPkYDwfgdRl8QquAtz1GcwXpJaK4z_0o&_nc_ht=scontent.xx&oh=e5b952a4adbbcd1b1af6b71b688f7284&oe=5CF9A64C",
"width": 50
}
},
"access_token": "XXXXXXXXXX",
"id": "253263371413138",
"tasks": [
"ANALYZE",
"ADVERTISE",
"MODERATE",
"CREATE_CONTENT",
"MANAGE"
]
}
Instead of looking of 'ADMINISTER' within the array, look for 'MANAGE'.
Full info here: https://developers.facebook.com/docs/pages/access-tokens