I am trying to use Facebook Graph API to get information about users who logged in via Facebook.
At the beginning, I was using only one function and no errors occurred; But then, I added another function that uses Facebook API. From that moment, none of the functions works. Only when I remove the new function, the old one works again...
I guess the code will be much understandable than what I described above:
function fb_login(){
FB.login(function(response) {
if (response.authResponse) {
access_token = response.authResponse.accessToken; //get access token
user_id = response.authResponse.userID; //get FB UID
FB.api('/me', function(response) {
user_email = response.email; //get user email
$.ajax({
type: "POST",
url: "http://*******/ajax.php",
data: { action: "login", id: user_id, email: user_email, first_name: response.first_name, last_name: response.last_name }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
} else {
//user hit cancel button
console.log('User cancelled login or did not fully authorize.');
}
}, {
scope: 'publish_actions,email,read_stream,publish_stream'
});
}
The function above will work unless the function below exists.
function update_autopost(form)
{
FB.api('/me', function(response) {
var autopost_value = form.autopost.checked;
if(autopost_value == false)
{
autopost_value = "off";
}
else{
autopost_value = "on";
}
$.ajax({
type: "POST",
url: "http://*********/ajax.php",
data: { action: "update", id: response.authResponse.userID, autopost: autopost_value }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
}
To be more detailed, after adding the second function, two things happens:
The first function stops working.
The second function is not able to get information from Facebook Graph API (for instance, response.authResponse.userID doesn't work).
Related
I am using Facebook Javascript SDK with a custom login button:
<button id="login" onclick="javascript:login();">Login Facebook</button>
and javascript function is:
function login() {
FB.login(function(response) {
// handle the response
FB.api('/me', { locale: 'en_US', fields: 'name, email' },
function(response) {
email = response.email;
name = response.name;
}
);
FB.getLoginStatus(function(response) {
user_id = response.authResponse.userID;
if (response.status === 'connected') {
console.log('Response goes here! ' + email + ' of ' + name + ' of ' + user_id);
$.ajax({
url: "includes/ajax_fb.php",
data:{email:email,name:name,user_id:user_id},
type: "POST",
success:function (data) {
if(!data.error) {
// location.reload(true);
$("#ajax-response").html(data);
}
}
});
} else if (response.status === 'not_authorized') {
alert(response.status);
} else {
alert(response.status);
}
});
}, {scope: 'public_profile,email'});
}
When I press login button once I am connected but no console.log and no data in #ajax-response are shown.
When I press login button for second time, console.log and data in #ajax-response are shown in console.
After the second button press, console.log and data in #ajax-response are shown with each consecutive button press.
I was pointed to How do I return the response from an asynchronous call? for a solution, and after thoroughly examining it, I understand I need to restructure my code to "Let functions accept callbacks". I've been trying to get it to work for hours now, and still cant figure it out :(
How do I restructure my code to make console.log and data in #ajax-response to show on the very first button press?
A Node.js / Express app with MongoDB, and using Passport, Passport Local and Passport Local Mongoose.
I'm trying allow registered users of my site to update their profiles. My idea was to rehash the signup form and logic, and send the updated data via a PUT request to the server.
The signup uses Ajax to submit the form, and whilst that works OK, when I send a PUT request to update the user, req.body comes back empty and the server throws out an error 500.
The update-form markup and javascript are nearly identical to the signup, so is it because I'm using a PUT request? I'm not even sure if I'm going about this in the right way...
Any pointers would be very happily received!
Edit user form submit logic:
$form.on('submit', function(e) {
if ($form.hasClass('is-uploading')) return false;
$form.addClass('is-uploading').removeClass('is-error');
if (isAdvancedUpload) {
e.preventDefault();
var ajaxData = new FormData($form.get(0));
if (droppedFiles) {
$.each(droppedFiles, function(i, file) {
ajaxData.append($input.attr('name'), file);
});
}
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'),
// data: ajaxData,
dataType: 'json',
cache: false,
contentType: false,
processData: false,
complete: function() {
$form.removeClass('is-uploading');
},
success: function(data) {
// $form.addClass(data.success == true ? 'is-success' : 'is-error');
// if (!data.success) console.log(data);
window.location.replace('/matches');
},
error: function(xhr, textStatus, errorThrown) {
console.log(xhr)
console.log(xhr.statusText);
console.log(textStatus);
console.log(errorThrown); }
});
} else {
var iframeName = 'uploadiframe' + new Date().getTime();
$iframe = $('<iframe name="' + iframeName + '" style="display: none;"></iframe>');
$('body').append($iframe);
$form.attr('target', iframeName);
$iframe.one('load', function() {
var data = JSON.parse($iframe.contents().find('body').text());
$form
.removeClass('is-uploading')
.addClass(data.success == true ? 'is-success' : 'is-error')
.removeAttr('target');
if (!data.success) $errorMsg.text(data.error);
$form.removeAttr('target');
$iframe.remove();
});
};
});
Server Side Edit Route:
// PUT edits
app.put('/users/:_id', function(req, res){
var spokenLangs = req.body.spokenlanguages.split(',');
var learnLangs = req.body.learninglanguages.split(',');
var comms = req.body.commethod.split(',');
var photos = []
req.files.forEach(function(file, i){
photos.push(req.files[i].path.replace('public/', '../'));
});
var updatedUser = new User(
{
username: req.body.username,
firstName: req.body.fname,
lastName: req.body.lname,
age: req.body.age,
gender: req.body.gender,
spokenLanguages: spokenLangs,
learningLanguages: learnLangs,
info: req.body.info,
country: req.body.country,
city: req.body.city,
comMethod: comms,
photos: photos,
lastLogin: Date.now()
}
);
User.findByIdAndUpdate(req.params._id, updatedUser, function(err, user){
if(err){
console.log('error updating user');
console.log(err);
} else {
res.redirect('/matches');
}
});
});
Thank you good people!
I need to get response['cloudUrl'] from my AJAX to my fb share dialog, all happening at the same time as user clicks on #sharebutton.
I can't put my code in AJAX success, if I wrap it in something else other than user click event, browser will most likely to block my fb share popup.
To make things clearer, I can get response['cloudUrl'] in the AJAX success callback.
function submitDataToFbShare(){
$.ajax(
{
url : 'www.testing.com/fb-data")',
type : 'POST',
data :
{
name: $('.nameField').val(),
personality_index: $('.nameField').val(),
country: $( "#countryList select:first-child option:selected").attr("value"),
},
dataType:'json',
success : function(response)
{
console.log("Successfully saved!");
console.log("response " + response['cloudUrl']);
},
error : function(request,error)
{
console.log("Error saving data!");
}
});
}
$('#sharebutton').click(function(e){
submitDataToFbShare();
e.preventDefault();
FB.ui({
method: 'feed',
link: "www.test.com",
name: "test",
description: "testing description",
picture: response['cloudUrl'],
}, function(response)
{
if (response != null || response != undefined)
{
console.log("success");
}
else
{
console.log("failed");
}
});
});
This question already has answers here:
Facebook OAuthException: "user hasn't authorized the application to perform this action"
(4 answers)
Closed 7 years ago.
I am trying to post on to the page of Fb from my javascript i am getting this error
(#200) The user hasn't authorized the application to perform this action
"OAuthException"
I am able to post the to my FB wall at the same time but not to the FB fan page where i am admin. Please guide me what is getting wrong. My code :
<input type="submit" class="btn"
onclick="postToFeed(); return false;"
value="Share with Friends"/>
<input type="submit" class="btn"
onclick="postToPage(); return false;"
value="Share On Page"/>
<p id='msg'></p>
<script>
FB.init({appId: '{!appId}', status: true, cookie: true});
function postToPage() {
var page_id = '1426984900889247';
FB.api('https://graph.facebook.com/' + page_id, {fields: 'access_token'}, function(resp) {
console.log(resp);
console.log(resp.access_token);
if(resp.access_token) {
FB.api('https://graph.facebook.com/' + page_id + '/feed',
'post',
{ message: "{!posDetails.Name}",
description :'{!posDetails.CMSR__Job_Description__c}',
link : '{!siteUrl}',
picture: '{!posDetails.CMSR__Linked_In_Url__c}',
caption: '{!posDetails.CMSR__Summary__c}',
access_token: resp.access_token }
,function(response) {
console.log(response);
});
}
});
alert(resp);
}
function postToFeed() {
var obj = {
method: 'feed',
link: '{!siteUrl}',
picture: '{!posDetails.CMSR__Linked_In_Url__c}',
name: '{!posDetails.Name}',
caption: '{!posDetails.CMSR__Summary__c}',
description: '{!posDetails.CMSR__Job_Description__c}'
};
function callback(response) {
if (response['post_id']) {
var postId = response['post_id'].split('_')[1];
document.getElementById('msg').innerHTML =
"Posted to your wall. "+
"<a href=\"https://www.facebook.com/permalink.php?"+
"id={!me.id}&v=wall&story_fbid="+postId+"\">View your post</a>";
}
}
FB.ui(obj, callback);
}
</script>
<script>
$( document ).ready(function() {
var nameID;
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
FB.api('/me/accounts', function(response){
console.log(response);
console.log(response.data);
var data= response['data'];
var ids = new Array();
var name = new Array();
console.log('data');
console.log(data);
console.log('ID');
console.log(ids);
for(var i=0; i<data.length; i++){
ids[i] = data[i].id;
name[i] = data[i].name;
if(ids[i] != null){
console.log(ids[i]);
if(nameID == 'undefined'){
nameID = ids[i]+':'+data[i].name+';';
}
else{
nameID = nameID+' '+ids[i]+':'+data[i].name+';';
}
}
}
setVar(nameID);
console.log('method called ');
console.log(ids);
console.log(name);
console.log(nameID);
});
}
else {
FB.login();
FB.api('/me/accounts', function(response){
console.log(response);
});
}
});
function setVar(param){
jQuery('[id$=myHiddenField]').val(param);
console.log('Param value '+param);
passStringToController();
}
});
</script>
Th error means you have not taken permissions. Get access tokens then try. To write to User feed you will need publish_actions permission.
I believe editing your Graph API call code will do the trick.
FB.api('https://graph.facebook.com/' + page_id + '/feed',
'post',
{
message: "{!posDetails.Name}",
description :'{!posDetails.CMSR__Job_Description__c}',
link : '{!siteUrl}',
picture: '{!posDetails.CMSR__Linked_In_Url__c}',
caption: '{!posDetails.CMSR__Summary__c}',
access_token: resp.access_token
},
function(response) {
console.log(response);
});
},
{scope: 'publish_actions'}
);
The last part is where you take permissions.
You should also try experimenting with your Graph API call before putting them up in code.
Here is a link for Graph call Explorer. Try experimenting here with the Access Tokens(Permissions) & API versions.
If you want a tutorial you will find it on this link http://lynda.com/Facebook-tutorials. Though it is not for Free it is worth it.
How can I get the names of the Facebook friends of the user?
I send requests to using FB.ui({ method: 'apprequests'?
Here is my code:
<input id="btSelectFriends" type="button" value="Select Friends" onclick="javascript:FBUISelectFriends()" />
<div id="fb-root"></div>
<script type="text/javascript" src="https://connect.facebook.net/en_US/all.js"></script>
<script type="text/javascript">
function FBUISelectFriends()
{
var selectedFriendsRequest_ids;
FB.ui({ method: 'apprequests', message: 'Select friends', data: 'tracking information for the user', tite: 'Select friends' },
function (response) {
if (!response || !response.request_ids) { alert('Request could not be sent'); return; }
selectedFriendsRequest_ids = response.request_ids;
for (var i = 0; i < selectedFriendsRequest_ids.length; i++) {
FB.api('/me/apprequests/?request_ids=' + selectedFriendsRequest_ids[i].toString(),
function (response) {
if (!response || response.error) { alert('Friends Selection error occured'); return; }
}
)
FB.api(selectedFriendsRequest_ids[0],
function (response)
{
alert(response.name);
}
);
}
}
);
return;
}
</script>
I tried this code but it didn't work:
FB.api(selectedFriendsRequest_ids[0], function (response) {console.log(response.name);});
Can you please help?
Thanks.
Just change this in your function
function FBUISelectFriends()
{
FB.ui(
{
method: 'apprequests',
redirect_uri: 'YOUR APP URL',
message: "Tom sent you a request"
},
function(response) {
if(response && response.hasOwnProperty('to')) {
for(i = 0; i < response.to.length; i++) {
//alert( response.to[i]);
// response.to[i] gives the selected facebook friends ID
// To get name of selected friends call this function below
getfbnames(response.to[i]);
}
}
}
);
}
function getfbnames(selectedfrndid)
{
var url = 'getfriendfbname.php'; // call a php file through URL and jquery ajax
$.ajax({
type:'POST',
url: url,
data : { fbid : selectedfrndid },
async: false,
success: function(data)
{
alert(data);
}
}); // end of ajax
}
A file getfriendfbname.php which returns the name of facebook friend name using friend facebook id in php
$fbid=$_POST['fbid'];
$json = file_get_contents('https://graph.facebook.com/'.$fbid);
$data = json_decode($json);
echo $data->name;
return $data->name;
Since 30 Sept. Facebook released a Requests 2.0 implementation of their system, which is a LOT more useful than the old one.
Here's why :
With the old one, your user first sent requests, Facebook returned to you the request_ids, then you had to verify who you sent the requests to...
With the new one, for each group of requests (like when a user sends multiple requests using multi-friend-selector) Facebook returns you one request id (parameter : response.request) and a parameter with all Facebook user ids requests were sent to (parameter : response.to)
You just have to activate Requests 2.0 in your app dashboard, then just change the conditions in your Javascript callback.
There's requests to retrieve information about your user's friends FB.api('/me/friends?fields=id,name,first_name,last_name and you just have to parse the result of this request with the Facebook user ids you sent requests to !
Everything is explained here about Requests 2.0 : http://developers.facebook.com/blog/post/569/