facebook using jquerymobile frame work - javascript

I am trying to implement the basic features of facebook like updating the facebook profile, and also facebook login using jquerymobile frame work. Using this link http://thinkdiff.net/facebook/graph-api-javascript-base-facebook-connect-tutorial/
It works fine with HTML 5 format. But when I integrate with the JqueryMobile, I am getting an error which says Uncaught exception: cant call method appendChild.
I will paste the code here: please have a look and let me know whats the problem.
<body>
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({appId: 'xxxxxxxxxxxxxx', status: true, cookie: true, xfbml: true});
/* All the events registered */
FB.Event.subscribe('auth.login', function(response) {
// do something with response
login();
});
FB.Event.subscribe('auth.logout', function(response) {
// do something with response
logout();
});
FB.getLoginStatus(function(response) {
if (response.session) {
// logged in and connected user, someone you know
login();
}
});
};
(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); //i am getting error in the is line
});
function login(){
FB.api('/me', function(response) {
document.getElementById('login').style.display = "block";
document.getElementById('login').innerHTML = response.name + " succsessfully logged in!";
});
}
function logout(){
document.getElementById('login').style.display = "none";
}
//stream publish method
function streamPublish(name, description, hrefTitle, hrefLink, userPrompt){
FB.ui(
{
method: 'stream.publish',
message: '',
attachment: {
name: name,
caption: '',
description: (description),
href: hrefLink
},
action_links: [
{ text: hrefTitle, href: hrefLink }
],
user_prompt_message: userPrompt
},
function(response) {
});
}
function showStream(){
FB.api('/me', function(response) {
//console.log(response.id);
streamPublish(response.name, 'Something ', 'hrefTitle', 'http://www.ffff.com', "Share www.ffffff.com");
});
}
function share(){
var share = {
method: 'stream.share',
u: 'http://www.fffffff.com'
};
FB.ui(share, function(response) { console.log(response); });
}
function graphStreamPublish(){
var body = 'hsdfkjasdkjfadkjf;adlfj';
FB.api('/me/feed', 'post', { message: body }, function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response.id);
}
});
}
function fqlQuery(){
FB.api('/me', function(response) {
var query = FB.Data.query('select name, hometown_location, sex, pic_square from user where uid={0}', response.id);
query.wait(function(rows) {
document.getElementById('name').innerHTML =
'Your name: ' + rows[0].name + "<br />" +
'<img src="' + rows[0].pic_square + '" alt="" />' + "<br />";
});
});
}
function setStatus(){
status1 = document.getElementById('status').value;
FB.api(
{
method: 'status.set',
status: status1
},
function(response) {
if (response == 0){
alert('Your facebook status not updated. Give Status Update Permission.');
}
else{
alert('Your facebook status updated');
}
}
);
}
</script>
<div data-role="page">
<div data-role="header">
<h1>Foofys-Facebook Page</h1>
</div><!-- /header -->
<div data-role="content">
<p>you are using foofys facebook app</p>
<div id="fb-root"></div>
<fb:login-button autologoutlink="true" perms="email,user_birthday,status_update,publish_stream"> </fb:login-button>
<p>
Publish Wall Post |
<!-- Share With Your Friends | -->
Publish Stream |
<!-- FQL Query Example -->
</p>
<textarea id="status" cols="50" rows="5">Write your status here'</textarea>
<br />
<!-- Status Set Using Legacy Api Call -->
<br /><br /><br />
<div id="login" style ="display:none"></div>
<div id="name"></div>
</div><!-- /content -->
<div data-role="footer">
<h4>Page Footer</h4>
</div><!-- /footer -->
</div><!-- /page -->
</body>
i am not able to understand whats happening in the code, BTW I have just pointed where exactly I am getting the error.

The trick with JQM and FB api is to use the graph API. That is DO NOT use the simple javascript FB wrappers since they are unstable when exposed to JQM's page handling - instead just use the new graph / rest API, check for and avoid multiple inits of the FB core and your'e set. For instance
function updateUserInfo(uid, accessToken) {
var uri = "https://graph.facebook.com/" + uid;
console.log("About to call FP.api with URI " + uri);
$.ajax({
type: "GET",
url: "https://graph.facebook.com/" + uid,
dataType: "json",
success:
(function (response) {
console.log("About to call check profile ...");
$("#p_name").val(response.name);
$("#email").val(response.email);
$("#fb_id").val(response.id);
$.ajax({
type: "POST",
url: "/check_profile",
cache: false,
data: {fb_id: response.id},
success: onCheckSuccess,
error: onError
});
console.log("FB id: " + response.id);
}),
error: onError
});

Related

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.

Facebook Post image to Facebook fan page with Javascript

It's funny really...
This is my script
var imgURL = "http://onseiekoerant.com/upload/uploads/1411504661_2786.jpg";
FB.api('/'MY PAGE ID'/photos', 'post', {
message: 'Website Genius',
url: imgURL,
access_token: accessToken
}, function (response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response.id);
//alert('Post ID: ' + response.post_id);
}
console.log(response);
});
When I call this function, it returns te restponse the the POST_ID. It's suposed to be successfull, but nothing is on my facebook fan page.
To give additional info, the access token cames from my currently signed in user of facebook, which is admin of the page.
What am I missing?

How to post to Facebook fanpage as fanpage, not user

How can I post on fanpage wall as fanpage not as a user - using javascript sdk.
RIght now on Init im receiving menage_pages and acquiring suitable fanpage id, how can i change call below?
var target = '/'+params.target+'/feed'
FB.api(target,
'post',
{ message: params.message,
link: params.link,
picture: params.picture,
caption: params.caption,
description: params.description,
name: params.name
}
,function(response) {
if (!response || response.error) {
$("#error").removeClass('hidden');
} else {
$("#success").removeClass('hidden');
}
});
You need the following permissions:
publish_stream
manage_pages
Now we call the page object to retrieve the page's access_token and then post with that token, something like:
function postToPage() {
var page_id = 'MY_PAGE_ID';
FB.api('/' + page_id, {fields: 'access_token'}, function(resp) {
if(resp.access_token) {
FB.api('/' + page_id + '/feed',
'post',
{ message: "I'm a Page!", access_token: resp.access_token }
,function(response) {
console.log(response);
});
}
});
}
Result:
More about this in my tutorial.
All you need is those three functionalities to be implemented:
First one is for setting the basic parameters for your Application(XXX-APP needs to be changed with your real id of application).
Second, function fol login to Facebook and granting needed permissions to be able to post to Facebook.
Third function is for posting to Facebook(XXX-page need to be changed with ID of the Page that you want to post something)
FB.init({ appId: 'XXX-APP', status: true, cookie: true, xfbml: true, oauth: true });
access_token = '';
function loginFB(){
FB.login(function(response) {
if (response.authResponse) {
access_token = FB.getAuthResponse()['accessToken'];
console.log('Access Token = '+ access_token);
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, {scope: 'publish_stream,manage_pages'});
}
function postToPage() {
FB.api('/XXX-page', {fields: 'access_token'}, function(resp) {
if(resp.access_token) {
FB.api('/' + page_id + '/feed',
'post',
{ message: "MSG", access_token: resp.access_token }
,function(response) {
console.log(response);
});
}
});
}

json.stringify is not a function error at JavaScript

I'm using login, registration Facebook API with JavaScript in a WordPress plugin. I got this error
json.stringify is not a function error at JavaScript.
What is the issue? I use this code:
<div id="fb-root"></div>
<script type="text/javascript">
var button;
var userInfo;
window.fbAsyncInit = function() {
FB.init({ appId: '154333274632806',
status: true,
cookie: true,
xfbml: true,
oauth: true});
showLoader(true);
function updateButton(response) {
button = document.getElementById('fb-auth');
userInfo = document.getElementById('user-info');
if (response.authResponse) {
//user is already logged in and connected
FB.api('/me', function(info) {
login(response, info);
});
button.onclick = function() {
FB.logout(function(response) {
logout(response);
});
};
}
else {
//user is not connected to your app or logged out
button.innerHTML = 'Login';
button.onclick = function() {
showLoader(true);
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me', function(info) {
login(response, info);
});
} else {
//user cancelled login or did not grant authorization
showLoader(false);
}
}, {scope:'email,user_birthday,status_update,publish_stream,user_about_me'});
}
}
}
// Run once with current status and whenever the status changes.
FB.getLoginStatus(updateButton);
FB.Event.subscribe('auth.statusChange', updateButton);
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol
+ '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
function login(response, info){
if (response.authResponse) {
var accessToken = response.authResponse.accessToken;
userInfo.innerHTML = '<img src="https://graph.facebook.com/' + info.id + '/picture">' + info.name
+ "<br /> Your Access Token: " + accessToken;
button.innerHTML = 'Logout';
showLoader(false);
document.getElementById('other').style.display = "block";
}
}
function logout(response){
userInfo.innerHTML = "";
document.getElementById('debug').innerHTML = "";
document.getElementById('other').style.display = "none";
showLoader(false);
}
//stream publish method
function streamPublish(name, description, hrefTitle, hrefLink, userPrompt){
showLoader(true);
FB.ui(
{
method: 'stream.publish',
message: '',
attachment: {
name: name,
caption: '',
description: (description),
href: hrefLink
},
action_links: [
{ text: hrefTitle, href: hrefLink }
],
user_prompt_message: userPrompt
},
function(response) {
showLoader(false);
});
}
function showStream(){
FB.api('/me', function(response) {
//console.log(response.id);
streamPublish(response.name, 'I like the articles of Thinkdiff.net', 'hrefTitle', 'http://thinkdiff.net', "Share thinkdiff.net");
});
}
function share(){
showLoader(true);
var share = {
method: 'stream.share',
u: 'http://thinkdiff.net/'
};
FB.ui(share, function(response) {
showLoader(false);
console.log(response);
});
}
function graphStreamPublish(){
showLoader(true);
FB.api('/me/feed', 'post',
{
message : "I love thinkdiff.net for facebook app development tutorials",
link : 'http://ithinkdiff.net',
picture : 'http://thinkdiff.net/iphone/lucky7_ios.jpg',
name : 'iOS Apps & Games',
description : 'Checkout iOS apps and games from iThinkdiff.net. I found some of them are just awesome!'
},
function(response) {
showLoader(false);
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response.id);
}
});
}
function fqlQuery(){
showLoader(true);
FB.api('/me', function(response) {
showLoader(false);
//http://developers.facebook.com/docs/reference/fql/user/
var query = FB.Data.query('select name, profile_url, sex, pic_small from user where uid={0}', response.id);
query.wait(function(rows) {
document.getElementById('debug').innerHTML =
'FQL Information: '+ "<br />" +
'Your name: ' + rows[0].name + "<br />" +
'Your Sex: ' + (rows[0].sex!= undefined ? rows[0].sex : "") + "<br />" +
'Your Profile: ' + "<a href='" + rows[0].profile_url + "'>" + rows[0].profile_url + "</a>" + "<br />" +
'<img src="' + rows[0].pic_small + '" alt="" />' + "<br />";
});
});
}
function setStatus(){
showLoader(true);
status1 = document.getElementById('status').value;
FB.api(
{
method: 'status.set',
status: status1
},
function(response) {
if (response == 0){
alert('Your facebook status not updated. Give Status Update Permission.');
}
else{
alert('Your facebook status updated');
}
showLoader(false);
}
);
}
function showLoader(status){
if (status)
document.getElementById('loader').style.display = 'block';
else
document.getElementById('loader').style.display = 'none';
}
</script>
<h3>New JavaScript SDK & OAuth 2.0 based FBConnect Tutorial | Thinkdiff.net</h3>
<button id="fb-auth">Login</button>
<div id="loader" style="display:none">
<img src="ajax-loader.gif" alt="loading" />
</div>
<br />
<div id="user-info"></div>
<br />
<div id="debug"></div>
<div id="other" style="display:none">
Publish Wall Post |
Share With Your Friends |
Publish Stream Using Graph API |
FQL Query Example
<br />
<textarea id="status" cols="50" rows="5">Write your status here and click 'Status Set Using Legacy Api Call'</textarea>
<br />
Status Set Using Legacy Api Call
</div>
You can find a link to the code for json.stringify here -
http://www.json.org/js.html
If you add that to your code then the error should go away.
Alternatively, you could add a reference to this script to your code -
<script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
What browser are you using? Not every browser supports native JSON parsing like you are trying. Also, it should be:
JSON.stringify

How to get FB.api('/me/feed', 'post', ... to work?

I've tried to use FB.api to post something to my feed for hours now. I can't get it to work for me. I gave the permissions to the app. I can post to my feed with the PHP SDK but I have to use JavaScript.
<button onclick="doPost()">Post to Stream</button>
<script>
window.doPost = function() {
FB.api(
'/me/feed',
'post',
{ body: 'Trying the Graph' },
Log.info.bind('/me/feed POST callback')
);
};
</script>
Can someone give me the example of a simple HTML page that uses FB.api to post to a feed?
Well, I got it working myself. I'm not sure what was wrong the first time as I started from scratch with a new HTML file. I hope it will help someone:
<!DOCTYPE html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
</head>
<body>
Post to Facebook
<script>
function postToFacebook() {
var body = 'Reading Connect JS documentation';
FB.api('/me/feed', 'post', { body: body, message: 'My message is ...' }, function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response);
}
});
}
</script>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'YOUR APP ID GOES HERE',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
};
(function() {
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>
</body>
</html>
I use this code on fb game-app
and looks like this http://trupa.files.wordpress.com/2012/04/prscreenan.jpg
<br><font style="color:#FFF; text-decoration:none;padding-left:27px;">post to wall</font><br>
<script>
function publishStory() {
FB.ui({
method: 'feed',
name: 'message name',
caption: 'message caption ',
description: 'description goes here',
link: 'the url current page',
picture: 'if you want to add an image'
},
function(response) {
console.log('publishStory response: ', response);
});
return false;
}
</script>
In first example you forgot "message" property. With out "message" you can post everyone, but not self.

Categories

Resources