Deleting action on Timeline using JS SDK - facebook

I have an 'Add To Timeline' button and I can already add posts to the timeline using another function, but now I want to be able to obtain the requestID of an action so that I can delete it from another javascript function I have. I been searching everywhere but can't find a good example so that I can learn how to obtain the ID, I'm still confused on how to do it. This is the code:
<script type="text/javascript">
function deleteRead(requestId)
{
FB.api(
requestId,
'delete',
function(response) {
if (!response || response.error) {
alert('error...');
} else {
alert('Successfully Deleted!');
}
});
}</script>
Adding the Action ID number of a post directly works and I'm able to delete the post on my timeline. But I have to make it where it automatically obtains the id for each post.
Do I have to use the PHP SDK in order to obtain the requestID? This is the other code I am using:
<div id="fb-root"></div>
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({
appId : 'I-have-my-app-ID-here', // App ID
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
};
// 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>
Even better, Is there a way where I can grab the requestID through PHP and pass it into a variable? depending on the post (if it's added to timeline), so that I can replace it with "requestID" to something like:
<?php echo $requestID; ?>
This way I can use the php code inside of my javascript where the requestID is and plus incase you want to use that same requestID that is obtained for something else in that same page. Example: if the post is added to Timeline it will show it's request ID number on that post page, incase you want to show the delete button only if its added to timeline, if it's not added, then don't show the delete button using a conditional statement.

There are two ways of doing this:
Store the IDs in a database for each action. This is not ideas as actions can be deleted from Facebook and can make it out of sync with your database.
Query the user's actions in real-time and use that to show a list of actions to delete. This is preferred.
Sample code:
// get activity from Facebook
$actions = $facebook->api('/me/' . $action_id );
// get ID of last action
echo $actions[0]['id'] );
You can then grab the ID of the post from above (e.g. $actions[0]['id']) and pass it to your JavaScript function or create a PHP function to delete the action. Optionally, you can loop through $actions to search if a particular action already exists, matching by URL, e.g.
if ( $actions[0]['data']['article']['url'] == $current_url ) {
...
}

Related

Requesting Assistance In Getting My Head Around Facebook Login for Websites

I'm wanting to implement the "Login With Facebook" that's common on websites but I'm having trouble grasping the whole concept and if anyone could assist me with this I'd be most appreciative.
I've been reading the documentation under this link https://developers.facebook.com/docs/facebook-login/ for days but I still don't "Get It".
Let's start with...
In the documentation, it says the JS SDK is easiest to use (for whom I dont know) but I'm thinking the NON JS version would be better and faster (and easier for me to grasp) but I don't know what to do. I'm "Stuck"
My main problem is I don't understand how I am suppossed to be able to insert an Auto Incrementing ID along with the person's first and last name into my DB. There's NOTHING or NOWHERE in the Facebook code where I could specify a DB, Table or Column so how is this data suppossed to get into my DB to log the user in??
I have a classifieds on my site of which I'm attempting to create a FB login for but as I said above, I'm stuck and could use help as I have only an intermediate level of knowledge regarding PHP and MySql
Like discussed in comments, here's example using JS SDK
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <!-- jQuery library, makes things easier. -->
<title>FB example</title>
</head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
// init the FB JS SDK
FB.init({
appId : YOUR_APP_ID, // App ID from the app dashboard
status : true, // Check Facebook Login status
xfbml : true // Look for social plugins on the page
});
// Additional initialization code such as adding Event Listeners goes here
};
// 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'));
/*
This function gets information about user and alrets user's name.
*/
function getUserInfo() {
FB.api('/me', function(response) {
$.ajax({
url: "ajax.php", //url to send ajax request to
data: {
json: response, // Key => value pairs of items to send
},
success: function(ajaxResponse) { // upon successful request
alert(ajaxResponse); //Alert whatever response we got.
}
})
})
}
/*
This function gets the login status of user
*/
function getLoginStatus() {
FB.getLoginStatus(function(response) {
if (response.status === 'connected') { //User is connected to Facebook and authorized your app
getUserInfo();
} else if (response.status === 'not_authorized') { //User is connected to Facebook, but hasn't authorized your app
login();
} else { //User is not connected to Facebook
login();
}
});
}
/*
Function promts user to log in and asks for permissions
*/
function login() {
FB.login(function(response) {
if (response.authResponse) {
getUserInfo();
} else {
alert('User cancelled login or did not fully authorize.');
}
}, {scope: 'email'}); // Comma separated permissions
}
</script>
<a href="javascript:getLoginStatus()"/>Login</a>
</body>
</html>
This is very simple example. On the page you will see link "Login". Upon pressing it you'll be either asked to login (if you're not logged into Facebook, or you haven't authorized app yet), or it will show popup with your name. Most of the code has been taken from JavaScript SDK documentation
EDIT:
To add user's data to your database, i would suggest making AJAX call from the getUserInfo() function. Replace alert part with ajax call to certain php file, which you will create and pass it the data from response variable (which contains data about user, like response.name and response.email). In the php file itself insert the information you got into database.
ANOTHER EDIT:
I've updated the code once again, namely i added jQuery library (easier for me to make ajax calls in it, although it's not much different from plain JS).
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
And updated getUserInfo() function to make ajax request to ajax.php.
In ajax.php i've made only one line:
print_r($_REQUEST['json']);
This will simply print out whatever data was send via ajax, and you will see it in popup. Next step would be checking out what information you get, and take whatever you need (it's $_REQUEST['json'] is simple array), and insert it into db.

Facebook javascript sdk An active access token must be used to query information about the current user

In my code I have
FB.api('/me/friends', function(response) {
if(response.data) {
//TODO : what to do if no. of friends is more than 5000 (pagination by fb)
friends_data=response.data;
dijit.registry.byId("mainWidget_div").set_friends_data(friends_data);
} else {
alert("Error!");
}
});
And this gives an error. But, if I call this function manually(on the console), there's no error
FB.api('/me/friends', function(response){r=response;});
//wait a while
r
and now r.data is an array of my friends.
I checked the network panel and I gather that when I call this manually, an access token automatically gets inserted in the request url and when it is getting called via the code, the access token doesn't get inserted.
The full fb sdk loading code in my application is this:
<script type="text/javascript">
// You probably don't want to use globals, but this is just example code
var fbAppId = "{{facebook_app_id}}";
// This is boilerplate code that is used to initialize the Facebook
// JS SDK. You would normally set your App ID in this code.
// Additional JS functions here
window.fbAsyncInit = function() {
FB.init({
appId : fbAppId, // App ID
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse page for xfbml or html5 social plugins like login button below
});
// Put additional init code here
dojo.ready(function(){
FB.api('/me/friends', function(response) {
if(response.data) {
//TODO : what to do if no. of friends is more than 5000 (pagination by fb)
friends_data=response.data;
dijit.registry.byId("mainWidget_div").set_friends_data(friends_data);
} else {
alert("Error!");
}
});
});
};
// 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'));
</script>
The answer from Brent Baisley and another answer to a different question, helped me figure out what was wrong.
You can't call FB.init() dependent methods right after FB.init() because it loads asynchronously. Even loading the data asynchronously like in dojo.ready() doesn't help. You have to wrap the code in FB.getLoginStatus().
My guess would be that you are trying to get the list of friends before the Facebook API is fully initialized. What is the error you are seeing?
You are registering the FB.api call to be run on DOM ready (dojo.ready). That might be causing it to load out of sync, even though it's all wrapped in fbAsyncInit. The friends API call itself has no dependency on the DOM, so I wouldn't wrap it in a dojo call. You're not doing that in the console and it's working.
I'm no javascript expert. If I made a possibly incorrect guess, the reason this happens could have to do with javascript hoisting.

How to implement logout with facebook connect in cakephp while preserving facebook login?

how do you logout the user from your site in facebook api, while still keeping the user logged into facebook with cakephp? (I found the answer so wanted to share with everyone).
I figured this one out just now, after reading CakePHP facebook integration logout issue with CakePHP-Facebook-Plugin.
Basically, although in the demos with webtechnick's examples, he puts the "Facebook.Connect" component in the AppController, if you want the selective logout piece, the Best place to put it is in reality within the actual controllers that you want to use it in. That or leave it in AppController and pass noAuth=> true into the Facebook.Connect component.
Either way, whichever way you choose, you set up one controller (facebook_controller.php?) to handle the facebook logins, and set its component with the noauth set to false (which is default, meaning DO authenticate [read connect.php to understand this]). That way, you have total control over when the users are logged into the site, and you can ACTUALLY log them out (with the regular redirect($this->Auth->logout()) without having the connect component immediately log them back in on redirect. Here is an implementation below:
Let me give you an idea:
app_controller.php
class AppController extends Controller {
var $components = array('Auth', 'Acl', 'Session');
//or if you want access to "$this->Connect" universally:
// array('Auth', 'Facebook.Connect' =>
// array('noauth'=>'true'), 'Acl', 'Session');
}
users_controller.php:
class UsersController extends AppController{
var $helpers = array('Facebook.Facebook');
//an example of the users controller, enabling connect, but
// not authorizing the user (because logout() used by Auth is here)
var $components = array('Email', 'Session', 'Facebook.Connect' => array('createUser'=>false, 'noauth'=>true));
//login() doesnt need to be shown and can be left alone for your traditional users
function logout(){
//if there is no fb user, do the logout normal
if ($this->Connect->FB->getUser() == 0){
$this->redirect($this->Auth->logout());
}else{
//ditch FB data for safety
$this->Connect->FB->destroysession();
//hope its all gone with this
session_destroy();
//logout and redirect to the screen that you usually do.
$this->redirect($this->Auth->logout());
}
}
}
your "facebook_controller.php":
class FacebookaController extends AppController {
...
// i dont personally like to have his piece create my user so:
var $components = array('Facebook.Connect' => array('createUser'=>false));
...
function login(){
//just need this stub function for later
$this->autoRender = false;
}
//you also need this for deauths or they will still be able to get into the site after deauth (against policy or whatever)
function deauthorize(){
//get user id from facebook API
$uid = $this->Connect->FB->getUser();
$record = $this->User->findByFacebookId($uid);
$this->User->delete($record['id'], FALSE);
}
}
now your users/login.ctp file:
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'your app id', // App ID
channelUrl : '//'+window.location.hostname+'/facebook/channel', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// Additional initialization code here
FB.Event.subscribe('auth.statusChange', function(response){
if (response.status == "connected"){
alert('redirecting you to auto facebook login');
//here is out default place for login
window.location.href = "http://"+window.location.hostname + "/facebook/login";
}
});
};
// Load the SDK Asynchronously
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
</script>
<?php e($this->Facebook->login(array('registration-url'=>'http://www.yoursite.com/facebook/signup'))); ?>
And that should be pretty much it. I hope this helps someone reading this who still needs the help.

How to track twitter follow us & facebook like us?

Is it possible to track users who like us or follow us on website. Also I want to track if some one unfollowing or unlike us. If there an api or any trick to do this?
Thanks to all
check out edge.create event - see more here: https://developers.facebook.com/docs/reference/javascript/FB.Event.subscribe/
edge.create - fired when the user likes something (fb:like).
edge.remove - fired when the user unlikes something (fb:like).
regarding capturing twitter event - see here: https://dev.twitter.com/docs/intents/events
Include widgets.js
<script type="text/javascript" charset="utf-8">
window.twttr = (function (d,s,id) {
var t, js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return; js=d.createElement(s); js.id=id;
js.src="//platform.twitter.com/widgets.js"; fjs.parentNode.insertBefore(js, fjs);
return window.twttr || (t = { _e: [], ready: function(f){ t._e.push(f) } });
}(document, "script", "twitter-wjs"));
</script>
Bind to an event when the user has clicked the Tweet Button:
twttr.events.bind('click', function(event) {
var click_type = event.region;
});
avs099 is correct and the link will provide some good info. But I thought I would post some further information to help others as they find this link.
I used the FB.init() function to call a setup function that creates the callback functions for the edge.create and edge.remove.
FB.Event.subscribe('edge.create',
function(response) {
alert('You liked the URL: ' + response);
//ajax back to the server.
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST", "YourCapturePage.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(response + "&add=1");
});
YourCapturePage.php or what ever processing page can then parse the response and add a record to your database back-end to track the usage of your like button on a given page. The response contains the info about what page was liked. Then you can do something similar for the edge.remove.

display hidden content once facebook like button clicked

On external website (not fb page) would like to put like button where once visitor click like button , it shows certain content.
Here is the code i might thinking it works if i'm not wrong but needs more help !
<div id="fb-root"></div>
<fb:like send="false" layout="button_count" width="100" show_faces="false"></fb:like>
<div id="hidden_content" style="display:none;">Thank You Dear</div>
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({
appId : '185373538XXXXXX', // App ID
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// Additional initialization code here
FB.Event.subscribe('edge.create', function() {
$('#hidden_content').show();
});
};
// 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>
So any idea !
~Thanks a lot
Here's my idea (since you're looking for ideas and references).
edge.create will only fire when a user likes the link. You will need to account for what happens when a user comes to your page that previously liked it. I would suggest looking for a way to determine if the like has showed up.
Here's some documentation to read thru:
This might get you the graph id of your web page's url via the object_url table
SELECT url, id, type, site FROM object_url WHERE url = "http://developers.facebook.com/"
Then see if you can track it down in either a stream posting or in a like