Skip to main content

Check if user liked page


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


Source: Tips4allCCNA FINAL EXAM

Comments

  1. 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!";
    }
    }

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

    ReplyDelete
  3. 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.

    ReplyDelete
  4. If I remember well, you need certain privileges to see if somebody's page fan. So you need request them first

    ReplyDelete
  5. 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.

    ReplyDelete

Post a Comment

Popular posts from this blog

Why is this Javascript much *slower* than its jQuery equivalent?

I have a HTML list of about 500 items and a "filter" box above it. I started by using jQuery to filter the list when I typed a letter (timing code added later): $('#filter').keyup( function() { var jqStart = (new Date).getTime(); var search = $(this).val().toLowerCase(); var $list = $('ul.ablist > li'); $list.each( function() { if ( $(this).text().toLowerCase().indexOf(search) === -1 ) $(this).hide(); else $(this).show(); } ); console.log('Time: ' + ((new Date).getTime() - jqStart)); } ); However, there was a couple of seconds delay after typing each letter (particularly the first letter). So I thought it may be slightly quicker if I used plain Javascript (I read recently that jQuery's each function is particularly slow). Here's my JS equivalent: document.getElementById('filter').addEventListener( 'keyup', function () { var jsStart = (new Date).getTime()...

Is it possible to have IF statement in an Echo statement in PHP

Thanks in advance. I did look at the other questions/answers that were similar and didn't find exactly what I was looking for. I'm trying to do this, am I on the right path? echo " <div id='tabs-".$match."'> <textarea id='".$match."' name='".$match."'>". if ($COLUMN_NAME === $match) { echo $FIELD_WITH_COLUMN_NAME; } else { } ."</textarea> <script type='text/javascript'> CKEDITOR.replace( '".$match."' ); </script> </div>"; I am getting the following error message in the browser: Parse error: syntax error, unexpected T_IF Please let me know if this is the right way to go about nesting an IF statement inside an echo. Thank you.