[javascript] How to check if a user likes my Facebook Page or URL using Facebook's API

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?!

This question is related to javascript facebook facebook-graph-api

The answer is


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.


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.


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'];
}

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' });

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to facebook

I am receiving warning in Facebook Application using PHP SDK React-Native: Application has not been registered error Can't Load URL: The domain of this URL isn't included in the app's domains Facebook OAuth "The domain of this URL isn't included in the app's domain" Facebook login message: "URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings." Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `ListView` Open Facebook Page in Facebook App (if installed) on Android App not setup: This app is still in development mode IOS - How to segue programmatically using swift Get ALL User Friends Using Facebook Graph API - Android

Examples related to facebook-graph-api

"Uncaught (in promise) undefined" error when using with=location in Facebook Graph API query Facebook OAuth "The domain of this URL isn't included in the app's domain" Facebook login message: "URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings." Facebook Graph API v2.0+ - /me/friends returns empty, or only friends who also use my application Creating a Facebook share button with customized url, title and image Facebook API "This app is in development mode" The developers of this app have not set up this app properly for Facebook Login? New og:image size for Facebook share? facebook: permanent Page Access Token? How to programmatically log out from Facebook SDK 3.0 without using Facebook login/logout button?