Reputation: 79
I have added facebook SDK in my web project, and i am printing all the values through id but i have one doubt.How to get the dynamic id value through jquery or javascript.
My Code
FB.api('/me', function(response) {
console.log('Successful login for: ' + response.name);
var fullname = document.getElementById('admin_name').innerHTML = response.name;
});
//Displaying through html
<span id="admin_name"></span>
and it's printing successfully.
But when i wants to get the id value through jquery or javascript it's coming null or empty.
//Jquery Code
$(document).ready(function () {
var adminName = $("#admin_name").text();
alert(adminName);
});
My Complete Login As Facebook Code
function statusChangeCallback(response)
{
console.log(response);
if (response.status === 'connected') {
testAPI();
}
}
function checkLoginState() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
window.fbAsyncInit = function() {FB.init({
appId : '12345678910',
cookie : true,
xfbml : true,
version : 'v2.2'
});
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
};
// Load the SDK asynchronously
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id))
return;
js = d.createElement(s);
js.id = id;
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
function testAPI() {
FB.api('/me', function(response) {
var fullname = document.getElementById('admin_name').innerHTML = response.name;
});
}
And Calling through FB Login Button
<fb:login-button max_rows="1"
size="large"
show_faces="false"
auto_logout_link="false"
onlogin="checkLoginState();">Login with Facebook
</fb:login-button>
Upvotes: 1
Views: 1856
Reputation: 627
Your problem is one of timing. The dom is going to grab what value is currently there, not one that will be there soon. At the time $(document).ready
is called, your FB.api
has not. Therefore, it will return null. Call the function after your FB.api is called.
Programmatically:
Stick your alert
code in a function
alertMe = function(){
$(document).ready(function () {
var adminName = $("#admin_name").text();
alert(adminName);
});
}
and call that function when your FB API is done doing its thing
FB.api('/me', function(response) {
console.log('Successful login for: ' + response.name);
var fullname = document.getElementById('admin_name').innerHTML = response.name;
alertMe(); //send the call for the alert
});
Upvotes: 1