Sunday, March 6, 2022

[FIXED] JQuery script doesn't fire in FB app for other participants

Issue

I'm learning to create a FB iframe tab app. For now I just want to check if the user that watches the page is an admin or not. So I have this code in my index.php:

<?php
require 'inc/facebook.php';

$facebook = new Facebook(array(
  'appId'  => 'xxxxxxxxxxxx',
  'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxx',
));

$user = $facebook->getUser();

$access_token = $facebook->getAccessToken();

if ($user) {
   try {
      $user_friendList = $facebook->api('/me/friends?access_token='.$access_token);
       $user_profile = $facebook->api('/me','GET');

    } catch (FacebookApiException $e) {
      error_log($e);
      $user = null;
    }
  }

$signed_request = $facebook->getSignedRequest();
$page_id = "";
if( $page = $signed_request['page'] ) {
    $page_id = $page['id'];
} else { $page_id = "some id"; }
?>


<!doctype html>
<html>
<head>
<title>php-sdk</title>
<link href="css/style.css" rel="stylesheet" type="text/css">
<script type="text/javascript">
    var page_id = <?php echo $page_id; ?>;
    var user_id = <?php echo $user; ?>;
    var is_admin = <?php echo $page['admin']; ?>;
</script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="scripts/functionality.js"></script>
...rest of the code...

Then in my functionality.js file I have this code, which should fire an alert dialog when the page loads:

$(function(){
    alert("Is admin: "+is_admin);
});

I'm the creator of the page where this app is being tested and the developer of the app. When I open this tab - I see the alert dialog pop-up as it should. I gave a Developer and a Tester role to 2 of my friends, and when they open the tab - the dialog doesn't pop-up for them. Any thoughts why is it happening and how to fix it?


Solution

The signed_request returns [admin] => 1 if the user is an admin or [admin] => otherwise. There is no true or false value. You can modify your code to something like:

<script type="text/javascript">
    var page_id = "<?php echo $page_id; ?>";
    var user_id = "<?php echo $user; ?>";
    var is_admin = "<?php echo isset( $page['admin'] ) && $page['admin'] == 1 ? true : false; ?>";
</script>


Answered By - Niraj Shah

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.