json.stringify is not a function error at JavaScript - 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

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 story posting issue

I am setting up for posting story on facebook but I am getting following alert:
You, or this app's Open Graph Test User, must have published this action at least once.
I am getting id in the response but when I am clicking on that I am redirecting to "Page not found".
Here is my code :
FB.api(
'me/objects/appnamespace:objecttype',
'post',
{
object :{
app_id: myappId,
objectype: myurl,
title: "Sample Organization",
image: mylogo,
description: ""
}
},
function(response) {
if (!response) {
alert('Error occurred.');
} else if (response.error) {
document.getElementById('result').innerHTML =
'Error: ' + response.error.message;
} else {
document.getElementById('result').innerHTML =
'<a href=\"https://www.facebook.com/me/activity/' +
response.id + '\">' +
'Story created. ID is ' +
response.id + '</a>';
}
}
);

facebook login script stopped working

I dont know what happened to my script, it was working great, then it suddenly doesnt return email (returns undefined), but the firstname, lastname and username work fine.
here is the code
<script type="text/javascript">
// initialize the library with the API key
FB.init({ appId: 'XXXXXXXXXX',status: true, cookie: true, xfbml: true, oauth: true });
function login() {
FB.login(function (response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function (response) {
console.log('Good to see you, ' + response.name + '.email :' + response.email);
console.log('Good to see you, ' + ",gender:" + response.gender + "another : " + response.first_name);
console.log('Good to see you, ' + response.username + '.last_name :' + response.last_name);
// console.log('Good to see you, ' + response);
}, { scope: 'email' });
} else {
console.log('User cancelled login or did not fully authorize.');
}
});
}
</script>
I havent changed anything though, what could be wrong ?
To get the email, { scope: 'email' } needs to be be passed to FB.login, not as a parameter to FB.api.
FB.login(function (response) {
...
}, { scope: 'email' });

(#3) App must be on whitelist facebook

I'm trying to post a messsage to a wall using FB.api
My perms are: 'email, read_stream, publish_stream' and my code is:
FB.getLoginStatus(function(response){
if(response.session) {
var accessToken = response.session.access_token;
var tokenUrl = "https://graph.facebook.com/me/feed?access_token=" + accessToken + "&callback=?";
var shareUserId = document.getElementById("shareHidden").value;
var shareTxtAreaMsg = document.getElementById("shareTxtArea").value;
console.log("friends user Id: " + shareUserId + " & " + "message: " + shareTxtAreaMsg);
var data = {
message: "shareTxtAreaMsg",
display: 'iframe',
caption: "Caption",
name: "Name",
picture: 'http://someDomain.com/Dev/img/share-force-wall-img.jpg',
link: "http://www.facebook.com/pages/someapp/XXXXXXXXXXX?sk=app_XXXXXXXXXXXXXX", // Go here if user click the picture
description: "Description field",
actions: [{ name: 'action_links text!', link: 'some link' }],
}
console.log(accessToken);
FB.api(tokenUrl, 'post', data, function(response){
if (response)
{
//console.log(response);
if (response.error)
{
console.log(response.error.message);
}
else
{
if (response.id)
console.log("Posted as post_id "+response.id);
else if (response.post_id)
console.log("Posted as post_id "+response.post_id);
else
console.log("Unknown Error");
}
}
});
}
});
When when try to post the message I'm getting a "(#3) App must be on whitelist" returned. Why is this happening?
Try FB.api('/me/feed'... instead of tokenUrl because FB.api will automatically add the full url prefix.

facebook using jquerymobile frame work

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
});

Categories

Resources