I am working on a facebook app. I have the following code which works fine if I run it like this
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '<?php echo $facebook->getAppId(); ?>',
session : <?php echo json_encode($session); ?>,
status : true,
cookie : true,
xfbml : true
);
$('#stgame').click(sendRequest);
function sendRequest() {
document.getElementById('gameSetup').style.display = 'block';
FB.ui({
method: 'apprequests',
message: '<?=$me[name];?> has invited you to a fun game of Towers. To play, just click on accept. Towers is a "3D" tile stacking word game.',
},
function (response) {
if (response && response.request_ids) {
var requests = response.request_ids.join(',');
$.post('handle_requests.php',{uid: <?php echo $uid; ?>, request_ids: requests},function(resp) {
window.location.replace("play.php?" + resp);
});
} else {
document.getElementById('gameSetup').style.display = 'none';
}
});
return false;
}
};
(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>
however, I need to alter it so that I can send a variable to "sendRequest" and change the trigger to an inline "onClick"
To do this I have created a link on the page like this:
<a><img src=/images/start.png onClick=sendRequest('1234556');></a>
and change the sendRequest function to sendRequest(variable) so that it can take the variable
However when I do this, each time I click on the button that has the onClick trigger, it gives me an error "cant find variable sendRequest"
I think this is because the onClick cant see the sendRequest function.
So my question is, how do I call that function from the onClick. bearing in mind that there will be multiple buttons on the page that will need to call the function giving the function a different variable value on each of them.
My current code looks like this:
<a><img src=/images/start.png onClick=sendRequest('123');></a>
<a><img src=/images/start.png onClick=sendRequest('456');></a>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '<?php echo $facebook->getAppId(); ?>',
session : <?php echo json_encode($session); ?>,
status : true,
cookie : true,
xfbml : true
}
);
function sendRequest(opponent) {
document.getElementById('gameSetup').style.display = 'block';
FB.ui({
method: 'apprequests',
to:opponent,
message: '<?=$me[name];?> has invited you to a fun game" tile stacking word game.',
},
function (response) {
if (response && response.request_ids) {
var requests = response.request_ids.join(',');
$.post('handle_requests.php',{uid: <?php echo $uid; ?>, request_ids: requests},function(resp) {
window.location.replace("play.php?" + resp);
});
} else {
document.getElementById('gameSetup').style.display = 'none';
}
});
return false;
}
};
(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>
If anyone could tell me how I can call this function I would appreciate it. as far as I am aware, the function needs to stay inside the window,fbAsyncInit function in order to actually work.
Any help would be greatly appreciated.
First of all, I haven't looked to all your code but I really think that you should do more effort on it (formatting and logic).
Anyway, to the point:
You can have a flag that will only set to true when the JS-SDK is loaded, and you can "block" any process outside the window.fbAsyncInit till the flag is set. Something like:
<div id="fb-root"></div>
<script>
var isLoaded = false;
window.fbAsyncInit = function() {
isLoaded = true;
...
...
}
function myFunc(myVar) {
if(isLoaded) {
// Do FB related stuff
}
}
I think the problem is that the sendRequest method is inside the function scope, so not available in the global namespace (where the dom could get to it). You might try changing:
function sendRequest()...
to
window.sendRequest = function()...
I should also mention that there is almost never a good reason to attach events directly to the dom like that. Even where you are rendering that JavaScript variable data in a templating language like php it is far better to set the variable values in an associative way that does not couple the event to the dom (but could couple the data to the element).
Related
Im trying to save the client IP address in a variable after retrieving it in JSON form from api.ipify.org. I can get the IP to show if I alert the result but cannot get it to save in a variable for some reason.
This works:
<script>
function getIP(json) {
alert(json.ip);
}
</script>
<script src="https://api.ipify.org?format=jsonp&callback=getIP"></script>
But this does not work:
<script>
var clientIP = ''
function getIP(json) {
clientIP = json.ip;
return clientIP;
}
alert(clientIP);
</script>
<script src="https://api.ipify.org?format=jsonp&callback=getIP"></script>
I would like to be able to store the data in a variable so that I can attach it to an embed that will add it into its automated webhook POST.
<!-- begin video recorder code --><script type="text/javascript">
var IPADDRESSVARIABLE = 'SOME_IP_ADDRESS'
var size = {width:400,height:330};
var flashvars = {qualityurl: "avq/300p.xml",accountHash:"BUNCHOFRANDOMSTUFF", eid:2, showMenu:"true", mrt:120,sis:0,asv:1,mv:0, payload: IPADDRESSVARIABLE};
(function() {var pipe = document.createElement('script'); pipe.type = 'text/javascript'; pipe.async = true;pipe.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 's1.addpipe.com/1.3/pipe.js';var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(pipe, s);})();
</script>
<div id="hdfvr-content"> </div>
<!-- end video recorder code -->
If I can get the IP address saved as a global variable then I can pass it into the 'payload' key of the 'flash vars'.
The second code example does not work because the variable is only given a value inside of a callback function, which means the alert,which runs synchronously, runs as soon as the javascript interpreter starts reading and running the code line by line, but the getIP function is only called later on when the jsonp request returns a response. Your first code example was the right way to go.
Your alert won't work because your code is not executing synchronously, getIP doesn't get called until after your alert statement. You need to trigger any functionality that depends on clientIP inside your getIP function. Here is an example:
function getIP(json) {
var event = new CustomEvent('iploaded', { detail: json.ip });
document.dispatchEvent(event);
}
document.addEventListener('iploaded', function(event) {
var IPADDRESSVARIABLE = event.detail;
var size = {width:400,height:330};
var flashvars = {qualityurl: "avq/300p.xml",accountHash:"BUNCHOFRANDOMSTUFF", eid:2, showMenu:"true", mrt:120,sis:0,asv:1,mv:0, payload: IPADDRESSVARIABLE};
(function() {var pipe = document.createElement('script'); pipe.type = 'text/javascript'; pipe.async = true;pipe.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 's1.addpipe.com/1.3/pipe.js';var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(pipe, s);})();
});
// simulate jsonp callback
getIP({ ip: '127.0.0.1' });
Also, no need to return in getIP
Try this :
function getIP(json) {
return json.ip;
}
var json = { "ip": "111.22.33.44"}
var clientIP = getIP(json);
alert(clientIP);
I found a workaround! I stored the result of the IP function into a hidden div to act as a container. I then declared a variable inside the embed code and set it to the innerHMTL. It may not be the most elegant but it does exactly what I want it to!
//hidden container to store the client IP address
<div id = 'ipContainer' style='display:none'></div>
//function to retrieve the client IP address
<script>
function getIP(json) {
document.getElementById('ipContainer').innerHTML = json.ip;
}
</script>
//shortened version of the URL that returns the IP
<script src='http://www.api.ipify.org'><script>
//embed code for the video recorder
<script>
<!-- begin video recorder code --><script type="text/javascript">
var clientIP = document.getElementById('ipContainer').innerHTML;
var size = {width:400,height:330};
//I passed the clientIP variable into the payload element of the flashvars object
var flashvars = {qualityurl: "avq/300p.xml",accountHash:"RANDOM ACCOUNT HASH", eid:2, showMenu:"true", mrt:120,sis:0,asv:1,mv:0, payload:clientIP}; //Here i passed the clientIP which is nor stored as a variable
(function() {var pipe = document.createElement('script'); pipe.type = 'text/javascript'; pipe.async = true;pipe.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 's1.addpipe.com/1.3/pipe.js';var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(pipe, s);})();
</script>
<div id="hdfvr-content"> </div>
<!-- end video recorder code -->
As Rob says, you're expecting the code to run synchronously but that isn't the case.
Here's a small edit of your code snippet that will work, basically I've wrapped the alert in a function, I then call that function once the getIP function has finished executing.
<script>
var clientIP = ''
function getIP(json) {
clientIP = json.ip;
alertClientIp();
}
function alertClientIp () {
alert(clientIP);
}
</script>
The code design of the above snippet is a bit nasty, if you only need to use the client IP once, then don't bother storing it as a variable, just pass it to the function which executes you "automated webhook POST" logic.
<script>
function getIP(json) {
clientIP = json.ip;
alertClientIp();
}
//Accept the client_ip as a param
function webhookLogic (client_ip) {
//Execute your logic with the client_ip,
//for simplicity I'll stick to your alert.
alert(client_ip);
}
</script>
With regards to your edit
It looks like you have the two sets of logic placed in two separate script elements, could you not merge them into one?
<script>
function getIP(json) {
clientIP = json.ip;
alertClientIp();
}
//Accept the client_ip as a param
function webhookLogic (client_ip) {
//Execute your logic with the client_ip,
//for simplicity i'll stick to your alert.
//Trigger your video wrapper code, unsure if
//if this method of execution will break your app...
videoWrapper(client_ip);
}
//Your video code from your latest edit
function videoWrapper (client_ip) {
var IPADDRESSVARIABLE = client_ip;
var size = {width:400,height:330};
var flashvars = {qualityurl: "avq/300p.xml",accountHash:"BUNCHOFRANDOMSTUFF", eid:2, showMenu:"true", mrt:120,sis:0,asv:1,mv:0, payload: IPADDRESSVARIABLE};
(function() {var pipe = document.createElement('script'); pipe.type = 'text/javascript'; pipe.async = true;pipe.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 's1.addpipe.com/1.3/pipe.js';var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(pipe, s);})();
}
</script>
If that chain of execution breaks your app then I think you need to go back to the drawing board with regards to the composition of your question, it's clear what you want to do but your question lacks a bit of meta-data as to how this logic all "fits together".
I am trying to use the Facebook Share in AngularJS. Below is my function that is called when the user clicks on the FB icon.
$scope.shareFB = function(){
// Get configuration ID from service
configuratorService.storeConfiguration($scope.modelCode, function(configID){
// Use saved configuration id to create share link
var base = $location.absUrl().replace($location.url(), '');
var byoUrl = base + "/" + $scope.modelCode + "/resume/" + configID;
console.log(byoUrl);
var fbpopup = window.open("https://www.facebook.com/sharer/sharer.php?u=" + byoUrl, "pop", "width=600, height=400, scrollbars=no");
});
}
This function works fine when I try to share a url like "https://www.google.com/"
the Facebook Popup then has the URL = "https://www.facebook.com/sharer/sharer.php?u=https://www.google.com/"
When I use the function above:
byoUrl = "http://localhost:8000/#/15K6/resume/9295316837"
and the resulting FB popup has URL = "https://www.facebook.com/15K6/resume/9295316837"
Why does the "/sharer/sharer.php?=http://localhost:8000/#/" get cut off?
You shouldn't even try to share a localhost URL, as Facebook will never be able to scrape it. That's very likely why your URL gets cut off. Facebook tries to resolve it and scrape it, but it will never find it, so it makes a best effort to redirect within itself. Example:
https://www.facebook.com/sharer/sharer.php?u=http://localhost:8000/#/coke
Try to put your share logic in the controller. Something along these lines.
// Share posts
$scope.fbShare = function(post){
FB.ui(
{
method: 'feed',
name: post.title,
link: 'http://www.cengkuru.com/'+post.slug,
picture: '',
caption: '',
description: $filter('limitTo')($scope.post.body, 150),
message: ''
});
}
<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>
I'm using PHP, Smarty, jQuery, AJAX, Colorbox - a jQuery lightbox, etc. for my website. There is some old code done using jQuery AJAX method to display the message in popup using standard jQuery library functions. Now I want to replace that typical popup using Colorbox popup. In short Iwant to change the design part only the message part is as it is. I tried to do this but couldn't succeeded yet. Can you help me in doing the necessary changes to the existing old code in order to show the messages in Colorbox popup instead of typical popup? For your reference I'm putting the old code below:
Code from smarty template to give a call to the jQuery AJAX function is as follows:
<span class="submit edit_user_transaction_status" value="{$control_url}{$query_path}?op=edit_user_transaction&page={$page}&txn_no={$user_transaction_details.transaction_no}&transaction_data_assign={$user_transaction_details.transaction_data_assign}&user_id={$user_id}{if $user_name!=''}&user_name={$user_name}{/if}{if $user_email_id!=''}&user_email_id={$user_email_id}{/if}{if $user_group!=''}&user_group={$user_group}&{/if}{if $user_sub_group!=''}&user_sub_group={$user_sub_group}{/if}{if $from_date!=''}&from_date={$from_date}{/if}{if $to_date!=''}&to_date={$to_date}{/if}{if $transaction_status!=''}&transaction_status={$transaction_status}{/if}{if $transaction_no!=''}&transaction_no={$transaction_no}{/if}">Update</span>
The code from js file which contains the existing AJAX code is as follows:
$(document).ready(function() {
//This function is use for edit transaction status
$(document).on('click', '.edit_user_transaction_status', function (e) {
e.preventDefault();
$.colorbox.close();
//for confirmation that status change
var ans=confirm("Are you sure to change status?");
if(!ans) {
return false;
}
var post_url = $(this).attr('value');
var transaction_status_update = $('#transaction_status_update').val();
$.ajax({
type: "POST",
url: post_url+"&transaction_status_update="+transaction_status_update,
data:$('#transaction_form').serialize(),
dataType: 'json',
success: function(data) {
var error = data.login_error;
$(".ui-widget-content").dialog("close");
//This variables use for display title and success massage of transaction update
var dialog_title = data.title;
var dialog_message = data.success_massage;
//This get link where want to rerdirect
var redirect_link = data.href;
var $dialog = $("<div class='ui-state-success'></div>")
.html("<p class='ui-state-error-success'>"+dialog_message+"</p>")
.dialog({
autoOpen: false,
modal:true,
title: dialog_title,
width: 500,
height: 80,
close: function(){
document.location.href =redirect_link;
}
});
$dialog.dialog('open');
}
});
});
});
Now the code snippet from PHP file which contains the PHP code and success message is as follows:
case "edit_user_transaction":
$transaction_no = $request['txn_no'];
$transaction_status_update = $request['transaction_status_update'];
$transaction_data_assign = $request['transaction_data_assign'];
$user_id = $request['user_id'];
$from_date = $request['from_date'];
$to_date = $request['to_date'];
$page = $request['page'];
if($request['transaction_no']!=''){
$query = "&transaction_no=".$request['transaction_no'];
}
// If public transaction status is entered
if($request['transaction_status']!='') {
$query .= "&transaction_status=".$request['transaction_status'];
}
// For checking transaction no is empty, blank, and numeric
if($transaction_no!='' && !empty($transaction_no)) {
$objUserTransactions = new UserTransactions();
$objUserPackages = new UserPackages();
//if transaction status update to success and transaction data not yet assign
if(empty($transaction_data_assign) && $transaction_data_assign == 0 && $transaction_status_update == "success") {
$user_transactions = $objUserTransactions->GetUserTransactionsDetailsByTransactionNo($transaction_no, $user_id);
$i = 0 ;
$j = 0 ;
//Create array related study and test
foreach($user_transactions['transaction_details'] as $my_cart) {
if(!empty($my_cart['pack_id'])) {
if($my_cart['pack_type'] == 'study') {
$data['study'][$i] = $my_cart['pack_id'];
$i++;
}
if($my_cart['pack_type'] == 'test') {
$data['test'][$j]['pack_id'] = $my_cart['pack_id'];
$data['test'][$j]['pack_expiry_date'] = $my_cart['pack_expiry_date'];
$data['test_pack_ids'][$j] = $my_cart['pack_id'];
$j++;
}
}
}
if(!empty($data['study'])) {
$objUserStudyPackage = new UserStudyPackages();
//Update packages sold count & purchase date in package table
$objUserStudyPackage->UpdateStudyPackagePurchaseData($data['study']);
//For insert packages related data to package_user table
foreach($data['study'] as $study_pack_id) {
$objUserPackages->InsertStudyPackagesToPackageUser($study_pack_id, $user_id);
}
}
if(!empty($data['test'])) {
$objUserTestPackage = new UserTestPackages();
//Update packages sold count & purchase date in test package table
$objUserTestPackage->UpdateTestPackagePurchaseData($data['test_pack_ids']);
//For insert test related data to test_user table
foreach($data['test'] as $test_pack_data) {
$objUserPackages->InsertTestPackagesToTestUser($test_pack_data['pack_id'], $test_pack_data['pack_expiry_date'], $user_id);
}
}
//This function is use for update status inprocess to success and transaction_data_assign flag 1
$user_transactions = $objUserTransactions->UpdateTransactionStatusByTransactionNo($transaction_no, $user_id, $transaction_status_update, '1');
} else {
// This function is use for update status
$user_transaction_details = $obj_user_transactions->UpdateTransactionStatusByTransactionNo($transaction_no, $user_id, $transaction_status_update);
}
//Email functionality when status update
include_once("transaction_status_update_email.php");
**$reponse_data['success_massage'] = "Transaction status updated successfully";
$reponse_data['title'] = "Transaction";
$reponse_data['href'] = "view_transactions.php?page=".$page."&from_date=".$from_date."&to_date=".$to_date.$query;
$reponse_data['login_error'] = 'no';
$reponse_data = json_encode($reponse_data);
echo $reponse_data;
die();**
}
break;
The code shown in bold font is the success response message. Can you help me in this regard, please? Thanks in advance.
Yo, you asked for help in PHP chat. Hopefully this helps:
So the dialog portion at the bottom needs to change to support colorbox. Firstly, load all your colorbox stuff. Second, you'll need to create your colorbox content dynamically by either grabbing content from an element on the page or building it on the fly.
You might need to debug some of this but here's generally how you do this...
Delete the entire $dialog variable
var $dialog = .....
And change that to something that will look similar to:
var $dialog = $('<div>').addClass('ui-state-success').append($('<p>').addClass('ui-state-error-success').html(dialog_message));
Then you'll need to do something like this:
$.colorbox({html: $dialog});
If you're having trouble seeing the content that is dynamically built inside your colorbox try calling $.colorbox.resize() on the opened callback:
opened: function(){
$.colorbox.resize();
}
If that doesn't work you may also need to pass a innerWidth/innerHeight or width/height property inside the resize method.
I have an issue with an FB.api only loading the first time a page is retrieved via AJAX. FB.getLoginStatus does work though.
Demo page: http://proof.ptly.com/test/fb/test-ajax.htm (clicking the load link works the first time but fails the second time it is clicked)
Expected/Desired behaviour: after giving permission to the app, it should list of all groups or pages associated to the user
Current behaviour: group list is only populated on first load. subsequent clicks do not load the list (FB.api does not return a response - view console for logging)
The reason behind this problem is that the page I am retrieving (test.htm) can't be changed but the page I am calling it from (test-ajax.htm) can. While I know this method isn't pretty nor ideal, I'm wondering if it is possible to overcome. Thus suggestions to change the underlying test.htm, while correct, won't solve the problem I'm having.
Sample code
Main page that calls the AJAX page
<html>
<head>
<title>My Facebook Login Page</title>
<script type="text/javascript" language="javascript" src="js/jquery.js"></script>
<script>
var loaded = false;
jQuery(document).ready(function(){
jQuery("#lnk").click(function(e){
e.preventDefault();
jQuery("#divContent").load("test.htm", function(){
if(loaded)
{
FB.getLoginStatus(FBverifyLogin);
}
else
{
loaded = true;
}
});
});
});
</script>
</head>
<body>
<a href="#" id='lnk'>load</a>
<div id='divContent'></div>
</body>
</html>
AJAX page being retrieved
<script type="text/javascript">
var FB_config = {
API_ID: "347798778614308",
PERMISSIONS: "publish_stream,manage_pages,user_groups",
};
(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));
jQuery(document).ready(function(){
// initialise FB
window.fbAsyncInit = function() {
FB.init({
appId : '347798778614308',
status : true,
cookie : true,
xfbml : true,
oauth : true
});
FB.Event.subscribe('auth.statusChange', FBverifyLogin);
};
});
function FBverifyLogin(response) {
console.log("FBverifyLogin");
console.log(response);
jQuery("#FBreauth").hide();
if (response.status === 'connected') {
// the user is logged in and has authenticated your
// app, and response.authResponse supplies
// the user's ID, a valid access token, a signed
// request, and the time the access token
// and signed request each expire
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
ShowPostToFacebookCheckbox();
FBdisplayMyPages(response.authResponse);
jQuery("#btnLogin").hide();
checkPermissions();
} else if (response.status === 'not_authorized') {
} else {
// the user isn't logged in to Facebook.
jQuery("#btnLogin").show();
return false;
}
}
function checkPermissions(){
console.log("checkPermissions");
FB.api('/me/permissions', function(response) {
console.log("in checkPermissions fb.api");
console.log(response);
var permissions = FB_config.PERMISSIONS.split(",");
for(var i = 0; i < permissions.length; i++)
{
if(response.data[0][permissions[i]] == undefined || response.data[0][permissions[i]] != 1)
{
jQuery("#FBreauth").show();
break;
}
}
});
}
function FBdisplayMyPages(authResponse){
console.log("FBdisplayMyPages");
console.log(authResponse);
FB.api('/me/accounts', function(response) {
console.log("in FBdisplayMyPages fb.api");
console.log(response);
var str = "";
var name = "";
var count = 0;
str += '<optgroup label="Pages">';
for(var i = 0; i < response.data.length; i++)
{
if(response.data[i].category != "Application")
{
name = response.data[i].name;
str += '<option value="'+response.data[i].id+"_"+response.data[i].access_token+'">'+name+'</option>';
count++;
}
}
str += "</optgroup>";
jQuery("#msgPostOn").html(str);
FB.api('/me/groups', function(response) {
console.log("in FBdisplayMyPages fb.api 2");
console.log(response);
str = jQuery("#msgPostOn").html();
str += '<optgroup label="Groups">';
name = "";
for(var i = 0; i < response.data.length; i++)
{
if(response.data[i].category != "Application")
{
name = response.data[i].name;
str += '<option value="'+response.data[i].id+"_"+authResponse.accessToken+'">'+name+'</option>';
count++;
}
}
str += "</optgroup>";
jQuery("#msgPostOn").html(str);
switch(count)
{
case 0:
// notify that there are not pages. will post to personal page
str += '<option value="' + authResponse.userID + "_" + authResponse.accessToken + '">Personal Account</option>';
jQuery("#msgPostOn").html(str);
jQuery("#FBpostTo").text("No pages found. Posting to your personal account");
jQuery("#FBpostTo").show();
break;
case 1:
// only 1 page. hide it...
// notify name of page to update
jQuery("#msgPostOn").hide();
jQuery("#FBpostTo").html("Posting to <strong>" + name + "</strong>");
jQuery("#FBpostTo").show();
break;
default:
// notify user to select a page to post to
jQuery("#FBpostTo").text("There are multiple groups/pages associated with your account. Specify which to post to ");
jQuery("#FBpostTo").show();
jQuery("#msgPostOn").show();
}
});
});
}
function FBrefresh(){
console.log("FBrefresh");
FB.getLoginStatus(FBverifyLogin);
}
function FBreauth(){
console.log("FBreauth");
FB.ui(
{
method: 'oauth',
display: 'popup',
app_id: FB_config.API_ID,
client_id: FB_config.API_ID,
redirect_uri: "http://www.facebook.com/connect/login_success.html",
scope: FB_config.PERMISSIONS
}
);
}
function ShowPostToFacebookCheckbox()
{
console.log("ShowPostToFacebookCheckbox");
jQuery('#postToFacebook2').css('display', 'inline');
jQuery('#LabelForFacebook').css('display', 'inline');
}
</script>
<div id="fb-root"></div>
<div id="postToFacebookField" class="fieldContainer checkbox ">
<div id="btnLogin" class="fb-login-button" scope="publish_stream,manage_pages,user_groups">Login with Facebook</div>
<input type="checkbox" style="display:none" name="postToFacebook2" value="on" id="postToFacebook2">
<label style="cursor: pointer; display:none" for="postToFacebook2" id="LabelForFacebook">Post to Facebook Page</label>
<div id="FBpostTo" style="display: none"></div>
<select id="msgPostOn" style="display: none"></select>
<div style="display: none" id="FBreauth">(Insufficient permissions. <a href ='#' onclick='FBreauth(); return false;'>Authorize this app</a> and <a href='#' onclick='FBrefresh() ; return false'>refreshing</a>)</div>
</div>
If you are still looking for a solution to this problem, I believe I have something that might work within the constraints that you have set. Quite simply, we just clear all the loaded variables and objects in memory, and from my tests, including the <script> that facebook attaches.
Replace the click handler in test.htm with this and it should work
jQuery(document).ready(function(){
jQuery("#lnk").click(function(e){
if(FB && document.getElementById("facebook-jssdk")){ //if set, reset
//removes the <script>
document.head.removeChild(document.getElementById("facebook-jssdk"));
window.FB=null; //unloads the APIs
loaded=null;
}
e.preventDefault();
jQuery("#divContent").load("test.htm", function(){
if(loaded)
{
FB.getLoginStatus(FBverifyLogin);
}
else
{
loaded = true;
}
});
});
});
We had a similar kind of issue, this post http://www.martincarlin.info/facebook-js-sdk-not-working-on-second-load-of-ajax-loaded-page/ helped us to resolve the issue.
The reason the script was not working was because the window.fbAsyncInit function runs on the initial page load and so the second time you do your AJAX call, the Facebook JavaScript SDK is already loaded in your page so window.fbAsyncInit doesn’t fire again.
By checking if FB is already defined we can then use our SDK code without the initialisation part.
Hope that will help you to resolve the issue.
After trying everything from past few days this below piece of code worked for me.
//intialize FB object (this is useful if you are using Turbolinks)
$(document).on('page:load', function(){
intializeFB();
});
intializeFB();
function intializeFB(){
if(typeof(FB) !== "undefined"){
delete FB;
}
$.getScript("http://connect.facebook.net/en_US/all.js#xfbml=1", function () {
FB.init({
appId : '19871816653254',
cookie : true, // enable cookies to allow the server to access
// the session
xfbml : true, // parse social plugins on this page
oauth : true,
status : true,
version : 'v2.4' // use version 2.4
});
});
}
Hope this is useful!
I think I'm going crazy. I can't get it to work.
I simply want to check if a user has liked my page with javascript in an iFrame app.
FB.api({
method: "pages.isFan",
page_id: my_page_id,
}, function(response) {
console.log(response);
if(response){
alert('You Likey');
} else {
alert('You not Likey :(');
}
}
);
This returns: False
But I'm a fan of my page so shouldn't it return true?!
I tore my hair out over this one too. Your code only works if the user has granted an extended permission for that which is not ideal.
Here's another approach.
In a nutshell, if you turn on the OAuth 2.0 for Canvas advanced option, Facebook will send a $_REQUEST['signed_request'] along with every page requested within your tab app. If you parse that signed_request you can get some info about the user including if they've liked the page or not.
function parsePageSignedRequest() {
if (isset($_REQUEST['signed_request'])) {
$encoded_sig = null;
$payload = null;
list($encoded_sig, $payload) = explode('.', $_REQUEST['signed_request'], 2);
$sig = base64_decode(strtr($encoded_sig, '-_', '+/'));
$data = json_decode(base64_decode(strtr($payload, '-_', '+/'), true));
return $data;
}
return false;
}
if($signed_request = parsePageSignedRequest()) {
if($signed_request->page->liked) {
echo "This content is for Fans only!";
} else {
echo "Please click on the Like button to view this tab!";
}
}
You can use (PHP)
$isFan = file_get_contents("https://api.facebook.com/method/pages.isFan?format=json&access_token=" . USER_TOKEN . "&page_id=" . FB_FANPAGE_ID);
That will return one of three:
string true string false json
formatted response of error if token
or page_id are not valid
I guess the only not-using-token way to achieve this is with the signed_request Jason Siffring just posted. My helper using PHP SDK:
function isFan(){
global $facebook;
$request = $facebook->getSignedRequest();
return $request['page']['liked'];
}
You can do it in JavaScript like so (Building off of #dwarfy's response to a similar question):
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<style type="text/css">
div#container_notlike, div#container_like {
display: none;
}
</style>
</head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'YOUR_APP_ID', // App ID
channelUrl : 'http(s)://YOUR_APP_DOMAIN/channel.html', // Channel File
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) {
var page_id = "YOUR_PAGE_ID";
if (response && response.authResponse) {
var user_id = response.authResponse.userID;
var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+"and uid="+user_id;
FB.Data.query(fql_query).wait(function(rows) {
if (rows.length == 1 && rows[0].uid == user_id) {
console.log("LIKE");
$('#container_like').show();
} else {
console.log("NO LIKEY");
$('#container_notlike').show();
}
});
} else {
FB.login(function(response) {
if (response && response.authResponse) {
var user_id = response.authResponse.userID;
var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+"and uid="+user_id;
FB.Data.query(fql_query).wait(function(rows) {
if (rows.length == 1 && rows[0].uid == user_id) {
console.log("LIKE");
$('#container_like').show();
} else {
console.log("NO LIKEY");
$('#container_notlike').show();
}
});
} else {
console.log("NO LIKEY");
$('#container_notlike').show();
}
}, {scope: 'user_likes'});
}
});
};
// 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 = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
</script>
<div id="container_notlike">
YOU DON'T LIKE ME :(
</div>
<div id="container_like">
YOU LIKE ME :)
</div>
</body>
</html>
Where the channel.html file on your server just contains the line:
<script src="//connect.facebook.net/en_US/all.js"></script>
There is a little code duplication in there, but you get the idea. This will pop up a login dialog the first time the user visits the page (which isn't exactly ideal, but works). On subsequent visits nothing should pop up though.
Though this post has been here for quite a while, the solutions are not pure JS. Though Jason noted that requesting permissions is not ideal, I consider it a good thing since the user can reject it explicitly. I still post this code, though (almost) the same thing can also be seen in another post by ifaour. Consider this the JS only version without too much attention to detail.
The basic code is rather simple:
FB.api("me/likes/SOME_ID", function(response) {
if ( response.data.length === 1 ) { //there should only be a single value inside "data"
console.log('You like it');
} else {
console.log("You don't like it");
}
});
ALternatively, replace me with the proper UserID of someone else (you might need to alter the permissions below to do this, like friends_likes) As noted, you need more than the basic permission:
FB.login(function(response) {
//do whatever you need to do after a (un)successfull login
}, { scope: 'user_likes' });
i use jquery to send the data when the user press the like button.
<script>
window.fbAsyncInit = function() {
FB.init({appId: 'xxxxxxxxxxxxx', status: true, cookie: true,
xfbml: true});
FB.Event.subscribe('edge.create', function(href, widget) {
$(document).ready(function() {
var h_fbl=href.split("/");
var fbl_id= h_fbl[4];
$.post("http://xxxxxx.com/inc/like.php",{ idfb:fbl_id,rand:Math.random() } )
}) });
};
</script>
Note:you can use some hidden input text to get the id of your button.in my case i take it from the url itself in "var fbl_id=h_fbl[4];" becasue there is the id example:
url:
http://mywebsite.com/post/22/some-tittle
so i parse the url to get the id and then insert it to my databse in the like.php file.
in this way you dont need to ask for permissions to know if some one press the like button, but if you whant to know who press it, permissions are needed.