The for loop runs through data (json) from the facebook api.
Now i would like to put the fb data in my own database (for usage in other sites)
The problem is not with reading the data, but somewhere in the submit
It looks like i'm only able to submit 1 time
I think that theForm[x] is the problem.
The code is:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = 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
});
// Here we subscribe to the auth.authResponseChange JavaScript event. This event is fired
// for any authentication related change, such as login, logout or session refresh. This means that
// whenever someone who was previously logged out tries to log in again, the correct case below
// will be handled.
FB.Event.subscribe('auth.authResponseChange', function(response) {
// Here we specify what we do with the response anytime this event occurs.
if (response.status === 'connected') {
// The response object is returned with a status field that lets the app know the current
// login status of the person. In this case, we're handling the situation where they
// have logged in to the app.
testAPI();
} else if (response.status === 'not_authorized') {
// In this case, the person is logged into Facebook, but not into the app, so we call
// FB.login() to prompt them to do so.
// In real-life usage, you wouldn't want to immediately prompt someone to login
// like this, for two reasons:
// (1) JavaScript created popup windows are blocked by most browsers unless they
// result from direct interaction from people using the app (such as a mouse click)
// (2) it is a bad experience to be continually prompted to login upon page load
FB.login(function() {
// handle the response
}, {scope: 'friends_relationships,friends_relationship_details,friends_photos,friends_about_me,user_about_me,friends_hometown,friends_location'});
} else {
// In this case, the person is not logged into Facebook, so we call the login()
// function to prompt them to do so. Note that at this stage there is no indication
// of whether they are logged into the app. If they aren't then they'll see the Login
// dialog right after they log in to Facebook.
// The same caveats as above apply to the FB.login() call here.
FB.login(function() {
// handle the response
}, {scope: 'friends_relationships,friends_relationship_details,friends_photos,friends_about_me,user_about_me,friends_hometown,friends_location'});
}
});
};
// 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;
js.src = "//connect.facebook.net/en_US/all.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
// Here we run a very simple test of the Graph API after login is successful.
// This testAPI() function is only called in those cases.
function testAPI() {
var $tokenx = $(FB.getAuthResponse()['accessToken']);
printTable($tokenx.selector);
};
function printTable(token){
FB.api('/me?fields=name,gender,friends.fields(relationship_status,name,gender,location,picture.width(200).height(200))', function(myList) {
var theForm = [];
for (var x = 0 ; x < myList.friends.data.length ; x++){
console.log(myList.friends.data[x].id + myList.friends.data[x].name);
// postPage(myList.friends.data[x].id, myList.friends.data[x].name);
var newInput1, newInput2;
// Start by creating a <form>
theForm[x] = document.createElement('form');
theForm[x].id = x;
theForm[x].name = x;
theForm[x].target = "hiddenFrame";
theForm[x].action = "insert.php";
theForm[x].method = 'post';
// Next create the <input>s in the form and give them names and values
newInput1 = document.createElement('input');
newInput1.type = 'text';
newInput1.name = 'id';
newInput1.value = myList.friends.data[x].id;
newInput2 = document.createElement('input');
newInput2.type = 'text';
newInput2.name = 'naam';
newInput2.value = myList.friends.data[x].name;
// Now put everything together...
theForm[x].appendChild(newInput1);
theForm[x].appendChild(newInput2);
theForm[x].submit();
//document.getElementById(theForm[x]).submit();
}
}
}
)};
/*
function postPage (id2,naam2) {
var theForm, newInput1, newInput2;
// Start by creating a <form>
theForm = document.createElement('form');
theForm.target = "hiddenFrame";
theForm.action = "insert.php";
theForm.method = 'post';
// Next create the <input>s in the form and give them names and values
newInput1 = document.createElement('input');
newInput1.type = 'text';
newInput1.name = 'id';
newInput1.value = id2;
newInput2 = document.createElement('input');
newInput2.type = 'text';
newInput2.name = 'naam';
newInput2.value = naam2;
// Now put everything together...
theForm.appendChild(newInput1);
theForm.appendChild(newInput2);
theForm.submit();
alert(id2 + " - " + naam2);
};
*/
</script>
<iframe src="insert.php" name="hiddenFrame"></iframe>
<form method="post" action="insert.php" target="hiddenFrame">
naam<input type="text" name="naam"><br>
id<input type="text" name="id">
<input type="submit" name="submit">
</form>
</body>
</html>
The insert.php looks like (removed database connection "host","user","pass","table"):
<?php
$db=mysql_connect("host","user","pass")or die(mysql_error());
mysql_select_db("table",$db);
$id = $_POST[id];
$naam = $_POST[naam];
$sql = "SELECT COUNT(*) AS count FROM USERS WHERE ID='$id'";
$result = mysql_query($sql);
$result = mysql_fetch_assoc($result);
$count = $result['count'];
echo $count;
echo " - ";
echo $id;
if($count > 0){
//found
}else{
$sql="INSERT INTO USERS(ID,NAME)VALUES('$id','$naam')";
mysql_query($sql,$db);
}
mysql_close($db);
?>
Sorry for the long code, but i didn't think partial was possible
Again I think that theForm[x] is the problem but i couldn't find it.
Already thanks if someone could point me in the right direction.
Ps. I know I have messy code :(
theForm[x].submit();
.submit() is like a click on the submit button.
So what happens in your script:
for Loop begins. (x = 0)
Creates Form[0]
Creates all Input fields and fills them with values
Submits the form (aka POST to insert.php) and "breaks" the for Loop.
Instead user jQuery's $.post from. It should look like this:
$.post('insert.php', {id: myList.friends.data[x].id, naam: myList.friends.data[x].name}, function(data){
// handle response here if required
});
If you get problems with duplicate posts/values, its probably because the $.post Request is asynchronous.
Have a look at this page for information on how to perform syncronous requests ...
http://api.jquery.com/jQuery.ajax/
I guess that you have only the first element of myList recorded in the database. That's because once you call .submit() your for loop is skipped and the page is refreshed. I'll suggest to avoid the usage of forms and just use simple ajax requests made with jQuery (I saw that you are already using it) -> http://api.jquery.com/jQuery.post/
Related
I am beginner in web development so please understand me. I am trying to create a session using php file and call it in javascript using ajax request. but after I input the path of the index.html in address bar, it always shows the index. I want to know how can i possibly do this with javascript and php. restricting the all the pages of the site if there is no user active.
for example logic:
if (userhasValue == true) {
//redirect to index and can access the whole website
} else {
// redirect to login page
}
I have tried the code below but it still redirecting to index.html even if the data recieve in ajax request is empty.
<?php
include('config.php');
session_start();
$user_check = $_SESSION['login_user'];
$temparray = array();
$ses_sql = mysqli_query($db,"select user_id,username,fullname from user where username = '$user_check'");
$row = mysqli_fetch_array($ses_sql,MYSQLI_ASSOC);
if ($row > 0 ){
array_push($temparray, $row); //save your data into array
echo json_encode($temparray);
} else {
echo 'Error';
}
?>
function getUser(){
var user ='';
var fullname ='';
var id ='';
var tempArray = '';
var name = '';
$.ajax({
type:'POST',
url:'../bench/php/session.php',
data:'',
success:function(msg){
alert(JSON.stringify(msg));
let tempArray = JSON.parse(msg)
user = JSON.stringify(tempArray[0]['username']);
fullname = JSON.stringify(tempArray[0]['fullname']);
id = JSON.stringify(tempArray[0]['id']);
document.getElementById('fullname').innerHTML = fullname;
if (msg == 'Error') {
window.location.href = "../pages-login.html";
}
}, error: function(e){
console.log(e);
}, complete: function(c){
console.log(c);
}
});
}
The code above does not restrict the accessibility of the index.html and other pages if the user is not logged in.
I want to restrict the index page and other pages if the user try to redirect to index page without logging in.
Please help me. Any help will much be appreciated! Thanks in advance
Situation: User load page and check if the user is Logged in facebook.
Problem: After the function .getLoginStatus (see js) I get the
ERROR message: Refused to display ...https://www.facebook.com/connect/ping? ... 'X-Frame-Options' to 'deny'
I have an other website which I didnt changed the FB-Code but there is not working anymore.
Data: v2.10
Checked: Firefox (fails), Chrome (fails), Edge (success)
I hope someone can help me.
Button
<div id="fb-root">
<div class="fb-login-button" data-max-rows="3" data-size="large" data-button-type="login_with" data-show-faces="false" data-auto-logout-link="false" data-use-continue-as="false" data-scope="public_profile,email"
data-mislogin="<?php echo isset ( $_SESSION ['userData'] [0] ['logInStatus'] )?'true':'false';?>" data-fbappId="<?php echo $fb_appId;?>"></div>
</div>
Javascript code Class
/**
* Facebook Login Handler
*/
var FBLoginHandler;
var isUserLog;
var isUserLoggedIn;
FBLoginHandler = new FBLoginHandler();
isUserLog = true;
FBLoginHandler.start();
function FBLoginHandler() {
this.start = function() {
var fb_graphVersion;
var fb_appId;
var fbLoginBt;
fb_graphVersion = 'v2.10';
fbLoginBt = $('.fb-login-button');
if (fbLoginBt.length > 0) {
fb_appId = fbLoginBt.attr('data-fbappId');
isUserLoggedIn = fbLoginBt.attr('data-mislogin');
if (isUserLoggedIn === 'false' || isUserLoggedIn === false) {
window.fbAsyncInit = function() {
FB.init({
appId : fb_appId,
autoLogAppEvents : false,
xfbml : true,
version : fb_graphVersion
});
FB.AppEvents.logPageView();
FBLoginHandler.checkLoginState();
}
this.createLoginBt(fb_graphVersion,fb_appId);
}
};
/*
* This function is called when someone finishes with the Login Button. See the onlogin handler attached to it in the sample code below.
*/
this.checkLoginState = function() {
// Now that we've initialized the JavaScript SDK, we call
// FB.getLoginStatus(). This function gets the state of the
// person visiting this page and can return one of three states to
// the callback you provide. They can be:
//
// 1. Logged into your app ('connected')
// 2. Logged into Facebook, but not your app ('not_authorized')
// 3. Not logged into Facebook and can't tell if they are logged into
// your app or not.
//
// These three cases are handled in the callback function.
FB.getLoginStatus(function(response) {
FBLoginHandler.statusChangeCallback(response);
});
}
/*
* The response object is returned with a status field that lets the app know the current login status of the person. Full docs on the response object
* can be found in the documentation for FB.getLoginStatus().
*/
this.statusChangeCallback = function(response) {
if (response.status === 'connected') {
// Logged into your app and Facebook.
FBLoginHandler.isFbLoginRight();
} else if (response.status === 'not_authorized') {
// The person is logged into Facebook, but not your app.
} else {
// The person is not logged into Facebook, so we're not sure if
// they are logged into this app or not.
}
}
/**
* AJAX Meldung sobald der Benutzer sich in Facebook eingelogt hat.
*/
this.isFbLoginRight = function() {
$.get(domain_https_basicfull_www
+ '/ajax/facebook/checkfblogin/?modus=x', function(result) {
//0=Fehler bei der Anmeldung, 1=Anmeldung Erfolgreich-Seite wird neu geladen.
var fbLoginResult = JSON.parse(result);
switch (fbLoginResult.resultNr) {
case '0' :
swal({
title : LanguageBasic.getString('Error') + '!',
html : 'Facebook',
type : 'error'
})
break;
case '1' :
location.reload();
break;
default :
break;
}
});
}
}
this.onLoginSubmit = function() {
$(".fb-login-button").off("onlogin");
$(".fb-login-button").on("onlogin", function(e) {
FBLoginHandler.checkLoginState()
return false;
});
}
this.createLoginBt = function(fb_graphVersion,fb_appId) {
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version="+fb_graphVersion+"&appId="+fb_appId;
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
}
}
I found this enter link description here
Its still the problem if I will check is the user Logged in but its possible to Log in if the user click self the fb button =)
Just got this same error, and what eventually worked for me was changing the site url in the app dashboard settings to my development URL. This is the answer that pointed me in the right direction after spending quite some time blocked -- https://stackoverflow.com/a/53325827/3787212
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.