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.
Related
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.
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.
I've been reading through other related questions here, but I think they are even too advanced for where I am at with Facebook's coding and such...
I want to have a Facebook Comment box on my website. That is no problem and it works fine. I also want to be notified, on Facebook, when someone leaves a comment. I've tried numerous different things with the comment.create but I really don't have a clue what I am doing.
Can someone take me through this step-by-step and help me understand what I need to do? Here is what I've got:
<body>
<script>
(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#xfbml=1&appId=362160727158879";
fjs.parentNode.insertBefore(js, fjs);
}
</script>
<div class="fb-comments" data-href="{site name}" data-num-posts="10" data-width="650" notify="true"></div>
WX, I have a Classifieds app on Facebook. I needed to create some notification to the owner of the advertisement also. I solved that with a simple way, after a comment I manipulate the response from FB with Ajax and Jquery:
FB.Event.subscribe('comment.create', function(response) {
//Send an email with ajax
$.ajax({
type: "POST",
url: "sendcommentemail.php?",
data: "urlofpage=",
beforeSend: function() {
$('#loading').show();
},
success: function(html){
$('#loading').hide();
},
error: function(html){
}
});
});
good luck!
What you need is just add a friend in the app settings on the page as moderator.
He/she will get notification in their Facebook profile each time someone is commenting on your website.
Also, this tool is very handy and to be Favorited for people with developer accounts:
https://developers.facebook.com/tools/comments
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 ) {
...
}
The initialization code:
window.fbAsyncInit = function() {
var bheight = $(document).height() + 50;
FB.init({
appId: appid,
frictionlessRequests : true,
status: true,
cookie: true,
xfbml: true,
oauth: true});
FB.Canvas.setSize({ width:760,height:bheight });
};
// 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));
The following code is called with an onclick:
function sendRequestViaMultiFriendSelector(msg){
FB.ui({
method: 'apprequests',
message: msg
});
}
The popup is shown and the user can select some friends, but after submitting or cancelling, the window goes blank. The pop up is still there but white and empty. No errors logged in Firebug.
If I add a callback function it's never reached.
I've tried adding a self closing redirect_uri (redirect_uri: 'http://.../self_close.html') but after submitting the popup redirects to self_close.html and even when the content of that html is just <script type="text/javascript">window.close(); </script> the popup won't close nor send the request to the selected friends.
Strangely enough a couple weeks ago this was working, you could select some friends and send them invitations and the popup would close.
My app is running in localhost, is in Sandbox mode and I've tried inviting other App's admins, test users, normal users, etc. In the past it used to work.
What could be happening now?
Similar questions that I've check:
FB.ui popup window doesn't close
Facebook app request dialog not sending request
http://facebook.stackoverflow.com/questions/4646441/how-to-close-a-facebook-sdk-dialog-opened-with-fb-ui
Thanks in advance!
UPDATE
I've added a test method using method:feed instead of method:apprequests
function feed_test() {
// calling the API ...
var obj = {
method: 'feed',
name: 'Feed test',
caption: 'Test',
description: 'Test'
};
function callback(response) {
document.getElementById('msg').innerHTML = "Post ID: " + response['post_id'];
}
FB.ui(obj, callback);
}
When I call upon this method with an onclick the popup is shown, I enter my comment, submit it and the popup goes blank too. The popup is not closing but the post is published in my wall.
UPDATE 2
I've realized that if I open the app in the browser, outside Facebook (using http://facebookapp.localhost/) the apprequest works fine and it opens the popup without the disabled address bar. When I try to invite friends inside FB the popup is shown with a gray address bar containing this:
https://www.facebook.com/dialog/apprequests?api_key=XXXXXXXXXX&app_id=XXXXXXXXXX&display=popup&frictionless=true&locale=en_US&message=XXXX&next=http%3A%2F%2Fstatic.ak.facebook.com%2Fconnect%2Fxd_arbiter.php%3Fversion%3D5%23cb%3Df2b013bbfaa712%26origin%3Dhttp%253A%252F%252Ffacebookapp.localhost%252Ff3267a4c771122%26domain%3Dfacebookapp.localhost%26relation%3Dopener%26frame%3Df3ad1f46b651196%26result%3D%2522xxRESULTTOKENxx%2522&sdk=joey
I wonder what could be the difference in using the app inside and outside FB, may be there are some js problems.
FIXED
Today I tryied again and the problem was gone. Also even when the popup wasn't closing and the callback function wasn't being called the invitations were sent. My test users forgot to check it they were getting them... anyway, mysterious bug, mysterious fix.