What is a replacement for FB.ensureInit() now? - facebook

I am loading FB API in asynchronous way:
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({appId: 'your app id', status: true, cookie: true,
xfbml: true});
};
(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>
How do I know when it is initialized? What is the replacement for FB.ensureInit() method that would prevent running enclosed code until API is initialized?

1° When you load Facebook's script it will execute window.fbAsyncInit, that you already have in your script. If you include a method call as the last row, inside that method you can be sure FB has been initialized.
The code above becomes
window.fbAsyncInit = function() {
FB.init({appId: 'your app id', status: true, cookie: true,
xfbml: true});
afterInit();
};
2° You can also define your own fbEnsureInit that works as previously and use a semaphore instead of a method call: (Originally from another answer.)
window.fbAsyncInit = function() {
FB.init({appId: 'your app id', status: true, cookie: true,
xfbml: true});
fbApiInitialized = true;
};
function fbEnsureInit(callback) {
if (!window.fbApiInitialized) {
setTimeout(function() { fbEnsureInit(callback); }, 50);
} else {
if (callback) { callback(); }
}
}
3° Yet another way is described in Performance tips for Connect wiki. This approach inspects the state of the script and does a callback when the script is loaded.
So, in your code above, before appending the script insert the following code:
script.onload = script.onreadystatechange = function() {
if ( !done && (!this.readyState || this.readyState == "loaded" ||
this.readyState == "complete") ) {
done = true;
afterInit();
}
};
The method afterInit will be called when the script is loaded.

Related

Facebook scrollTo()

I'm having a very bizzare issue with Facebook's scrollTo(). Here's my relevant code:
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'APPID',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse XFBML
oauth : true // enable OAuth 2.0
});
FB.Canvas.setSize({ width: 810, height: 5000 });
//FB.Canvas.setAutoGrow();
};
(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 scrollToQuestion(top) {
FB.Canvas.scrollTo(0, top);
}
</script>
Here's the bizzare issue, the code on it's own does NOT work. HOWEVER while using firebug and putting a breakpoint right on the FB.Canvas.scrollTo(top, 0); line than the functionality works. What's going on...?!
EDIT: Finally figured it out... for some odd reason top variable was coming in as a string of some sort. I had to change the call to the function like this:
var top = 0;
top = parseInt($('.top'"]').position().top);
scrollToQuestion(top);
This fixed my issue.

facebook plugins not refreshing together

i have two Facebook plugins(like and comment box) on my page.
when i login with on plugin it not logins another plugin automatically until i refresh page.
for example : when i login by clicking on like button,my comment box remains in logout state until i refresh page.
please suggest me something good for that problem
my code is as follow
<script>
window.fbAsyncInit = function () {
FB.init({ appId: 'My app ID', status: true, cookie: true, xfbml: true });
FB.Event.subscribe("xfbml.render", function (targetUrl) {
$("#myh1").html("Facebook Loaded");
//alert('edge.create');
setTimeout(aaa, 500);
});
FB.Canvas.setDoneLoading(function () {
alert("Done loading");
});
FB.Event.subscribe('comment.remove', function (response) {
alert('The status of the session is: ' + response.status);
});
};
(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 aaa() {
$("#content_1").mCustomScrollbar({
scrollButtons: {
enable: false
}
});
}
</script>
<div class="fb-like" data-send="false" data-href="http://www.facebook.com /AiLiveCaptions" data-width="298" data-show-faces="true">
</div>
<div class="fb-comments" data-href="http://www.facebook.com/AiLiveCaptions" data-num- posts="8" order_by="reverse_time" data-width="280"></div>
You can use
FB.XFBML.parse();
to render XFBML markup in a document on the fly.
FB Documentation

Facebook "FB.Canvas.getPageInfo", how to use it properly

I need help figuring out how to appropriately use the FB.Canvas.getPageInfo from Facebook's javascript sdk:
https://developers.facebook.com/docs/reference/javascript/FB.Canvas.getPageInfo/
I'm able to get the info and log/alert the data:
function getFbCanvasInfo() {
FB.Canvas.getPageInfo(function(fbCanvasInfoObject) {
console.log(fbCanvasInfoObject);
});
}
$("a.GetScrollTest").live( "click", function() {
getFbCanvasInfo();
return false;
});
But I can't figure out how to set that data and then apply it to other elements or functions (i.e. like something below):
$("a#test-link").each(function() {
var fbPosition = getFbCanvasInfo().scrollTop;
$(this).append("<em>The scroll top value is " + fbPosition + "px");
}
I know its not right and I'm missing something here.
BTW these functions are all below my async init and FB root, which appears like so:
<div id="fb-root"></div>
<script type="text/javascript">//<!--
window.fbAsyncInit = function()
{
FB.init({
appId: '223615011031939',
status: true,
cookie: true,
xfbml: true,
oauth:true,
channelUrl: '[MY PROJECTS CHANNEL URL]'
});
var isLoaded = true;FB.Canvas.setSize();FB.Canvas.setAutoGrow(500);
};
(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);
}());
;(function($){
$(document).ready(function($){
[THE JQUERY FROM ABOVE HERE]
});
})(jQuery);
//--></script>
Much appreciation to anyone who has advice/expertise! Thanks!
The getPageInfo returns a readonly object. To "set" things, you would need to use the provided setter functions listed in the documentation. One of them to set the size of the canvas is setSize see https://developers.facebook.com/docs/reference/javascript/FB.Canvas.setSize/
Also you should cleanup your javascript so the async nature of working with their API is good.
$("a.GetScrollTest").live( "click", function() {
FB.Canvas.getPageInfo(function(fbCanvasInfoObject) {
var fbPosition = fbCanvasInfoObject.scrollTop;
$(this).append("<em>The scroll top value is " + fbPosition + "px");
});
return false;
});

Facebook Connect does not process jQuery ajax call after successful login

I've got the following script:
<script>
window.fbAsyncInit = function () {
FB.init({ appId: '<%: Facebook.FacebookApplication.Current.AppId %>',
status: true,
cookie: true,
xfbml: true,
oauth: true
});
function FBLogin() {
FB.login(function (response) {
if (response.authResponse) {
ConnectFacebookUser(response.authResponse.accessToken);
} else {
alert('User cancelled login or did not fully authorize.');
}
}, { scope: 'email' });
}
$('#fb-button').live('click', function (e) {
FBLogin();
e.preventDefault();
});
function ConnectFacebookUser(at) {
var postdata = "at=" + at;
alert('This is the access token : ' + at);
$.ajax({
type: "POST",
dataType: "json", // what data type to expect from the server
url: "/FBConnect.ashx",
data: postdata,
success: function (data) {
// do nothing
alert('all good');
},
error: function (xhr, status, error) {
alert('error occured in FBConnect.ashx');
}
});
alert('finished');
}
};
(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>
And for the html fragment:
Login with facebook
<div id="fb-root"></div>
When the link is clicked, a popup window for facebook shows up and when i enter my login details, i only see an alert to say "This is the access token..." but the rest of the code don't get processed. If I click the "login with facebook" link one more time, then everything gets processed as normal.
What could be the problem?
It works for me. I get the message 'this is the acccess code' and then i get a 'finished' alert. Check your Chrome debugger tools to look for any script errors that may be occuring silently.
Check out https://github.com/xocialhost/jquery.xocialCore.js/blob/master/jquery.xocialCore.js to see a jQuery specific way of doing this. One thing I noticed is that the jQuery click function when calling the FB.login was triggering the popup blocker in a few browsers I was testing with. I set this up to work around that issue but it's also a way to add a callback that is run properly during the init sequence.

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.