I am grabbing the facebook pages a user admins and displaying them in a select box through the Facebook JS SDK.
What's the best way to take the array I get back from facebook response.data and iterate so it goes into the select?
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js">
</script>
<script>
FB.init({
appId:'119406238144386', cookie:true,
status:true, xfbml:true
});
FB.api('/me/accounts/', function(response) {
alert(response.data);
});
</script>
<select id="pages"></select>
<fb:login-button perms="manage_pages">Connect to Facebook</fb:login-button>
Facebook returns the object in an object array, so just loop through each one and add a new html object item to the select list.
A full working example without jQuery:
<!DOCTYPE html>
<html>
<body>
<div id="fb-root"></div>
Get Pages
<select id="pages" style="display:none;"></select>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({ appId: 'your app id', status: true, cookie: true, xfbml : true });
function getPages() {
FB.login(function(response) {
if (response.session && response.perms) {
FB.api('/me/accounts/', function(response) {
var pages = document.getElementById('pages');
pages.style.display = 'block';
for(var i =0; i < response.data.length; i++)
{
pages[i] = new Option(response.data[i].name);
}
}
);
}
} , {perms:'manage_pages'});
}
</script>
</body>
</html>
FB.api('/me/accounts/', function(response) {
for i in response.data {
var option = $('<option></option>')
.attr("val",response.data[i])
.html(reponse.data[i]);
$('#pages').append(option);
}
});
i'm just assuming response.data is giving back an array.
Related
I am trying to create a facebook javascript application - that will take an array of facebook id's -- and display them as a list.
Johnny Cash
Roger Maleon
Mealine Pip
[23432432, 1313232, 43534543]
here is the
latest jsfiddle
http://jsfiddle.net/0ht35rpb/94/
-- I've started to try and make the application but its coming up with the error
""An active access token must be used to query information about the current user.""
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
var facebookArray = [23432432, 1313232, 43534543]
var app = {
getFriends : function(){
FB.api('/me?fields=id,name', function(response) {
console.log(response)
if(response.data) {
$.each(response.data,function(index,friend) {
alert(friend.name + ' has id:' + friend.id);
});
} else {
alert("Error!");
}
});
}
}
$(document).ready(function() {
$.ajaxSetup({ cache: true });
$.getScript('//connect.facebook.net/en_US/sdk.js', function(){
FB.init({
appId: '803898723110754',
version: 'v2.7' // or v2.1, v2.2, v2.3, ...
});
$('#loginbutton,#feedbutton').removeAttr('disabled');
FB.getLoginStatus();
app.getFriends();
});
});
//app id
//803898723110754
//client token
//a10b3f9479bac9cce58aeecd8a037a04
</script>
</head>
<body>
</body>
</html>
There are several ways to load reCAPTCHA using javascript such as below:
<html>
<head>
<title>Loading captcha with JavaScript</title>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script type='text/javascript'>
var captchaContainer = null;
var loadCaptcha = function() {
captchaContainer = grecaptcha.render('captcha_container', {
'sitekey' : 'Your sitekey',
'callback' : function(response) {
console.log(response);
}
});
};
</script>
</head>
<body>
<div id="captcha_container"></div>
<input type="button" id="MYBTN" value="MYBTN">
<script src="https://www.google.com/recaptcha/api.js?onload=loadCaptcha&render=explicit" async defer></script>
</body>
</html>
This code load captcha on pageload. I want load reCAPTCHA just when clicked on "MYBTN". So the code changes into:
<html>
<head>
<title>Loading captcha with JavaScript</title>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script type='text/javascript'>
$('#MYBTN').on('click',function(){
var captchaContainer = null;
var loadCaptcha = function() {
captchaContainer = grecaptcha.render('captcha_container', {
'sitekey' : 'Your sitekey',
'callback' : function(response) {
console.log(response);
}
});
};
});
</script>
</head>
<body>
<div id="captcha_container"></div>
<input type="button" id="MYBTN" value="MYBTN">
<script src="https://www.google.com/recaptcha/api.js?onload=loadCaptcha&render=explicit" async defer></script>
</body>
</html>
But this code didn't work when I click on "MYBTN" and reCAPTCHA not load.
Help me plz. Thanks.
You just need to call loadCaptcha()
$('#MYBTN').on('click',function(){
var captchaContainer = null;
var loadCaptcha = function() {
captchaContainer = grecaptcha.render('captcha_container', {
'sitekey' : 'Your sitekey',
'callback' : function(response) {
console.log(response);
}
});
};
loadCaptcha(); // THIS LINE WAS MISSING
});
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<div id="captcha_container"></div>
<input type="button" id="MYBTN" value="MYBTN">
<script src="https://www.google.com/recaptcha/api.js?onload=loadCaptcha&render=explicit"></script>
Simple situation
Html
<input type="button" id="MYBTN" value="create captcha">
<div id="captcha_container"></div>
JS
var testSitekey = '6LeLzA4UAAAAANNRnB8kePzikGgmZ53aWQiruo7O';
$('#MYBTN').click(function() {
$('body').append($('<div id="captcha_container" class="google-cpatcha"></div>'));
setTimeout(function() {
grecaptcha.render('captcha_container', {
'sitekey': testSitekey
});
}, 1000);
});
Online demo (jsfiddle)
You just mentioned onload in your embedded script. Either you just remove onload from your embedded script or just keep your code outside of the onclick event in the function name loadCaptcha.
1. First Solution:
$('#MYBTN').on('click',function(){
var captchaContainer = null;
var loadCaptcha = function() {
captchaContainer = grecaptcha.render('captcha_container', {
'sitekey' : 'Your sitekey',
'callback' : function(response) {
console.log(response);
}
});
}
});
<script src="https://www.google.com/recaptcha/api.js?render=explicit"></script>
2. Second Solution
<script type='text/javascript'>
var captchaContainer = null;
var loadCaptcha = function() {
captchaContainer = grecaptcha.render('captcha_container', {
'sitekey' : 'Your sitekey',
'callback' : function(response) {
console.log(response);
}
});
};
</script>
<script src="https://www.google.com/recaptcha/api.js?onload=loadCaptcha&render=explicit" async defer></script>
In first Solution your code will work when you click your button. Even you don't have to put then in loadCaptcha function you can directly call grecaptcha.render.
But when you mention onload in your script tag then it will not work according to your click then it will find the callback function you mentioned in the script. And as you wrote the loadCaptcha in onload of script and you wrote this function inside the onClick event. When the script tag executed, the code tried to find the loadCaptcha function which was not initialised till the script tag executed (as it would initialise on click event), So your script was not working.
JS
// Loading captcha with JavaScript on button click
jQuery(document).ready(function ($) {
$('#MYBTN').on('click',function() {
$.getScript( "https://www.google.com/recaptcha/api.js?render=__YOUR_KEY__" )
.done(function( script, textStatus ) {
if(typeof grecaptcha !== "undefined") {
grecaptcha.ready(function () {
grecaptcha.execute('__YOUR_KEY__', {
action: 'homepage'
})
.then(function (token) {
var recaptchaResponse = document.getElementById('captcha_container');
recaptchaResponse.value = token;
});
// Your other code here
// You can control captcha badge here
});
}
});
});
});
HTML
// Required HTML:
<body>
<input type="button" id="MYBTN" value="MYBTN">
<div id="captcha_container"></div>
</body>
I've implemented the captcha to be loaded only after one of the required fields of my form was focus. I also implemented a check variable to see if the captcha's dependencies were inserted before.
Here is is:
jQuery('#MyRequiredInputId').focus(function () {
if(typeof loadedRecaptcha != 'undefined'){
return;
}
jQuery.getScript("https://www.google.com/recaptcha/api.js?render=___YOURKEY__")
.done(function (script, textStatus) {
if (typeof grecaptcha !== "undefined") {
grecaptcha.ready(function () {
var siteKey = '___YOURKEY___';
jQuery('body').append(jQuery('<div id="captcha_container" class="google-cpatcha"></div>'));
setTimeout(function() {
grecaptcha.render('captcha_container', {
'sitekey': siteKey
});
}, 1000);
});
}
loadedRecaptcha = true;
});
});
Note that in my case, I have a <div id= "captcha_container"></div> where I want to display my captcha.
Result:
I got the same issue today when I discovered that there are about 21 requests for Google Recaptcha even without open the login modal, this is indeed too much ):
After trying this method:
HTML
<div class="row">
<div class="col-sm-12 btm10">
<div id="captcha_container"></div>
</div>
</div>
JS
<script>
var Sitekey = '<?php echo config('google_key') ?>';
$('#loginbtn').click(function() {
$('body').append($('<div id="captcha_container" class="google-cpatcha"></div>'));
setTimeout(function() {
grecaptcha.render('captcha_container', {
'sitekey': Sitekey
});
}, 1000);
});
</script>
finally, I get the results I want, now the recaptcha only loads when the login modal opens (based onClick function).
Unfortunately, I found that the main Google Recaptcha script still loads in console even while using the delay method mentioned above because the main script is declared on the page head:
<script src="https://www.google.com/recaptcha/api.js"></script>
So, I removed it from the page head then combined some lines of codes together to get it to work and only loads when the modal opens as follow:
Final code:
<div class="row">
<div class="col-sm-12 btm10">
<div id="captcha_container"></div>
</div> //Wherever you want the reCaptcha to appear
</div>
<script>
//Add to the header or the footer it doesn't matter
var Sitekey = '<?php echo config('google_key') ?>';
$('#loginbtn').click(function() {
$.getScript("https://www.google.com/recaptcha/api.js") //The trick is here.
$('body').append($('<div id="captcha_container" class="google-cpatcha"></div>'));
setTimeout(function() {
grecaptcha.render('captcha_container', {
'sitekey': Sitekey
});
}, 1000);
});
</script>
You can view it in action here:
https://youtu.be/dAZOSMR8iI8
Thank you
Tell Google you want to render the recaptcha explicitly (when you are ready). https://www.google.com/recaptcha/api.js?render=explicit
After the api script has run grecaptcha is available globally.
<!DOCTYPE html>
<html lang="en">
<head> </head>
<body>
<div id="whereIWantRecaptcha"></div>
<button id="myButton">show Recaptcha</button>
<script
src="https://www.google.com/recaptcha/api.js?render=explicit"
async
defer
></script>
<script>
var button = document.querySelector('#myButton');
button.addEventListener('click', function(){
grecaptcha.render('whereIWantRecaptcha', {
'sitekey' : '6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI'
});
});
</script>
</body>
</html>
I'm trying to login on my website with Facebook JS API from my iPhone. The login works fine on computer as well as iPad.
Here's the login screen:
On iPhone however, I get to a screen which looks like this:
When I close the Facebook screen with the "Back to previous page" message and reload the login page, I'm logged in successfully. It looks like the problem is, that iPhone is unable to close the login pop-up screen.
Here's my JavaScript code:
<div id="fb-root"></div>
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({
appId : '', // the app id
status : true,
cookie : true,
xfbml : true
});
FB.getLoginStatus(function(response) {
if (response.status == "connected") {
// do something
}
});
FB.Event.subscribe("auth.login", function(response) {
if (response.status == "connected") {
// do something
}
});
};
function facebookRedirectLogin(redirect) {
// do something
}
function logout() {
FB.logout(function(response) {
// do something
});
}
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
</script>
<div class="fb-login-button" style="margin-bottom: 20px;">Forbind med Facebook</div>
How can I fix this problem?
Checkout this URL,
please do the settings as mentioned in the above URL, this code is working in mobile devices.
<html>
<head>
<title>My Facebook Login Page</title>
</head>
<body>
<div id="fb-root"></div>
<div id="login">
<p><button onClick="loginUser();">Login</button></p>
</div>
<div id="logout">
<p><button onClick="FB.logout();">Logout</button></p>
</div>
<script>
function loginUser() {
FB.login(function(response) { }, {scope:'email'});
}
</script>
<script>
(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);
}());
</script>
<script>
window.fbAsyncInit = function() {
FB.init({ appId: 'xxxxxxxxxxxx',
status: true,
cookie: true,
xfbml: true,
oauth: true});
FB.Event.subscribe('auth.authResponseChange', handleResponseChange);
};
</script>
<script>
function handleReponseChange(response) {
document.body.className = response.authResponse ? 'connected' : 'not_connected';
if (response.authResponse) {
alert(response);
}
}
</script>
</body>
I have the exact same problem. This may (or may not) be an open Facebook bug: https://developers.facebook.com/bugs/280811108698311
I have been seeing questions on Stack Overflow to access the Facebook friends list of a user. I have tried in many different ways to do this and unfortunately nothing seems to be working for me.
Can any one tell me the exact problem I am facing? I'm totally new to javascript. Below is the code I am using
<html>
<head>
<title>My Facebook Login Page</title>
</head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
var friends = new Array();
FB.init({
appId : 'some_id', // App ID
channelUrl : 'http://apps.facebook.com/myapp', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
FB.api('/me/friends', function(response) {
if(response.data) {
$.each(response.data,function(index,friend) {
alert(friend.name + ' has id:' + friend.id);
});
} else {
alert("Error!");
}
});
};
// Load the SDK Asynchronously
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "http://connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
</script>
<p>
<fb:profile-pic uid='loggedinuser' facebook-logo='true'/>
</p>
</br>
</br>
"Welcome, <fb:name uid='' useyou='false'></fb:name>
</br>
</br>
</br>
</br>
</br>
</br></br> <fb:login-button autologoutlink="true" />
</body>
</html>
I am getting the response as undefined and am not able to even login to facebook. I tried using the following sample http://jobyj.in/api/get-facebook-friends-using-javascript-sdk/. This works fine with the Demo but then I downloaded it and tried to run from my machine it is also not giving me any result.
Any suggestions for me?
Update
I am using the example given by #Somnath below and able to login. But after that getting the value undefined for response.session resulting in zero friends list. Any idea for this?
Here is tutorial for login through javascript.
Tutorial Javascript SDK
Ist try to log in. Otherwise you will get undefined response.
FB.getLoginStatus(function(response) {
if (response.session) {
// logged in and connected user, someone you know
FB.api('/me/friends', function(response) {
if(response.data) {
$.each(response.data,function(index,friend) {
alert(friend.name + ' has id:' + friend.id);
});
} else {
alert("Error!");
}
});
}
});
You will get friend list of logged in user.
Updated Answer:
Don't specify channelUrl at time of initialization. Only give only following four parameters. Try this out.
FB.init({
appId : 'some_id', // App ID
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
Update2:
Try using fql:
if (response.session) {
//getting current logged in user's id from session object
globaluserid=response.session["uid"];
//fetching friends uids from 'friend' table. We are using FB.api syntax
FB.api(
{
method: 'fql.query',
query: 'SELECT uid1 FROM friend WHERE uid2='+globaluserid
},
function(response) {
//once we get the response of above select query we are going to parse them
for(i=0;i<response.length;i++)
{
//fetching name and square profile photo of each friends
FB.api(
{
method: 'fql.query',
query: 'SELECT name,pic_square FROM user WHERE uid='+response[i].uid1
},
function(response) {
//creating img tag with src from response and title as friend's name
htmlcontent='<img src='+response[0].pic_square+' title='+response[0].name+' />';
//appending to div based on id. for this line we included jquery
$("#friendslist").append(htmlcontent);
}
);
}
}
);
} else {
// no user session available, someone you dont know
top.location.href="../kfb_login.php";
}
I am trying to add events information to the facebook users profile from a 3rd party website using Javascript SDK provided by facebook. I just googled for few tutorials and I got this links
http://thinkdiff.net/facebook/graph-api-javascript-base-facebook-connect-tutorial/
http://www.masteringapi.com/tutorials/how-to-ask-for-extended-permission-in-your-facebook-application/32/
http://www.masteringapi.com/tutorials/how-to-create-facebook-events-using-graph-api/49/#using_the_js-sdk
I tried with the combination of login logout and session handling
this is the code which I am run just to test whether it works or not.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<div id="fb-root"></div>
<script type="text/javascript">
window.fbAsyncInit = function()
{
FB.init({
appId: '207712505927107',
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);
}());
function login()
{
FB.api('/me', function(response)
{
document.getElementById('login').style.display = "block";
var loggedInMessage = response.name + " successfully logged in!";
document.getElementById('login').innerHTML = loggedInMessage;
});
}
function logout()
{
document.getElementById('login').style.display = "none";
}
//addevent to facebook profile
function addevents()
{
FB.api('/me/events', 'post', {
name: "JS-SDK Event",
start_time: 1272718027,
location: "Beirut",
privacy_type: "OPEN"
}, function(resp) {
alert(resp.id);
});
}
</script>
<p>
<fb:login-button
autologoutlink="true"
perms="email,user_birthday,status_update,publish_stream,create_event">
</fb:login-button>
</p>
<p>
Add Events
</p>
<br />
<br />
<br />
<br />
<div id="login" style ="display:none"></div>
<div id="name"></div>
</body>
</html>
When I click on the add event page I am getting "undefined". Iam not able to add events to facebook profle. Kindly help me
I would try your code again, and maybe console.log(resp) in your callback method for the addevents function. I tested your code on fbrell.com and it seemed to work perfectly and as expected.
edit: after a little research (and your fixed code..) I found that the fb:login button doesn't ensure that your application has the correct permissions that the perms parameter requests. We find this out when we do a Graph request and it fails. So we catch the error, and then launch the Login modal via the FB.login method, and ask for the create_event permission. When the user accepts that dialog, we retry creating the event.
<fb:login-button
autologoutlink="true"
perms="email,user_birthday,status_update,publish_stream,create_event">
</fb:login-button>
create
<script>
FB.XFBML.parse();
document.getElementById('create_event').onclick = function() { create_event(); }
function create_event()
{
FB.api('/me/events', 'post', {
name: "JS-SDK Event",
start_time: 1272718027,
location: "Anywhere USA",
privacy_type: "OPEN"
}, function(resp) {
if (typeof resp.error != 'undefined')
{ /*this failed. most likely because we don't have the extended permission
for create_event. so lets check for it, ask for it, and try to create
the event again. but first, we'll make sure that the error message says
something about 'create_event' so we don't launch an infinite loop
*/
if (resp.error.message.match(/create_event/))
{
FB.login(function(response)
{
if (response.session
&& response.status == 'connected'
&& response.perms.match(/create_event/))
{
//this user is connected & we have create event permission.
create_event();
}
},
{
perms: 'create_event'
});
}
}
});
}
</script>
Working code on fbrell.com: http://fbrell.com/saved/17c7b60eab91e6736a2a10c87d53c5b8
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<div id="fb-root"></div>
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({appId: '207712505927107', 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);
}());
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";
}
//add events
function addevents() {
FB.api('/me/events','post',{
name:"awesome event",
start_time:1272718027,
location:"Bengaluru",
privacy_type:"OPEN",
description:"U r invited !!!"
}, function(resp) {
document.write(resp.id);
});
}
//checking persmission
function check_perm() {
FB.api({ method: 'users.hasAppPermission', ext_perm: 'create_event' }, function(resp)
{
if (resp === "1") {
alert('Permission granted');
} else {
alert("Permission not granted");
}
});
}
</script>
<p>Please click on Login button first </p>
<p><fb:login-button autologoutlink="true" perms="create_event"></fb:login-button></p>
<p> Please click on check permissions first </p>
check permissions
<p> now u r all set to add events to facebook </p>
<p>
Add Events
</p>
<br /><br /><br />
<div id="login" style ="display:none"></div>
<div id="name"></div>
</body>
</html>