dsafew1231 2013-01-09 17:56
浏览 146

Facebook API和Ajax POST请求

I have a Facebook connect/disconnect link. When user clicks on "Facebook connect" link (on index.php), it checks the user state (Is he connected to Facebook or not?) then if he's not connected, my script sends an Ajax $.post request to connect.php in order to retrieve infos from database (for instance : Is the user registered in our database?). After that, it sends back a response to index.php : if there is no error, the page is refreshed. In this case, if everything is ok, after the page is refreshed by the script (window.location.reload();), we should see the Facebook user ID (UID).

The problem is the UID is still empty after the page is reloaded through the ajax callback. But, if I refresh the page manually one more time, I can now see the UID.

I test many ways to understand where the problem comes from, and I found there is a problem with this Facebook request : $me = $facebook->api('/me');

Anyway, I can't do without $me = $facebook->api('/me'); so if you want to test my script and find the problem, here is what you need ! (don't forget the last Facebook SDK) ;-)

Any help would be very apreciated ! Thanks !

index.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Facebook Connect</title>
<script src="js/jquery.js"></script>
<?php

/* FACEBOOK APP CONFIGURATION */
$appId = 'YOU_APP_ID';
$appSecret = 'YOUR_APP_SECRET';

define("APPID",$appId);
define("APPSECRET",$appSecret);

/* API CALL */
if (!class_exists('FacebookApiException'))
{
  require_once('inc/facebook.php' );
}

$facebook = new Facebook(array(
   'appId' => APPID,
   'secret' => APPSECRET,
));

$fb_user = $facebook->getUser();

if ($fb_user) {
    try
    {
       $me = $facebook->api('/me');
       $uid = $facebook->getUser();
    }
      catch (FacebookApiException $e)
    {
       //echo error_log($e);
       $fb_user = null;
    }
}
?>
</head>

<body>
<div id="fb-root"></div>
<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/fr_FR/all.js#xfbml=1&appId=<?=APPID?>";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>

<script type="text/javascript">
    window.fbAsyncInit = function() {
        FB.init({
            appId   : '<?=APPID?>',
            oauth   : true,
            status  : true,
            cookie  : true,
            xfbml   : true
        });
    };

    function fb_connect() {
        alert('FB.getLoginStatus');
        FB.getLoginStatus(function(response) {
            if (response.status === 'connected') {
                var access_token = response.authResponse.accessToken;
                var user_id = response.authResponse.userID;
                //
                window.location.reload();
                //
            } else {
                alert('FB.login');
                FB.login(function(response) {
                    var access_token = response.authResponse.accessToken;
                    var user_id = response.authResponse.userID;
                        $.post('connect.php', function(data) {
                        var obj = $.parseJSON(data);
                        if (obj['error']==0) {
                            alert(obj['message']);
                            window.location.reload();
                        } else {
                            alert(obj['message']);
                        }
                    });
                    //

                }, {
                    scope: 'email, publish_stream, user_birthday'
                });
            }
        });
    }

    function fb_logout() {
        FB.logout(function(response) {
            window.location.reload();
        }); 
    }

    (function() {
      var e = document.createElement('script');
      e.src = document.location.protocol + '//connect.facebook.net/fr_FR/all.js';
      e.async = true;
      document.getElementById('fb-root').appendChild(e);
    }());
</script>
<p>UID : <?=$fb_user?></p>
<?php if ($fb_user) { ?>
<a href="#" onclick="fb_logout();">Disconnect</a>
<?php } else { ?>
<a href="#" onclick="fb_connect();">Facebook connect</a>
<?php } ?>
</body>
</html>

connect.php

<?php
/* FACEBOOK APP CONFIGURATION */
$appId = 'YOUR_APP_ID';
$appSecret = 'YOUR_APP_SECRET';

define("APPID",$appId);
define("APPSECRET",$appSecret);

/* API CALL */
if (!class_exists('FacebookApiException'))
{
  require_once('inc/facebook.php' );
}

$facebook = new Facebook(array(
   'appId' => APPID,
   'secret' => APPSECRET,
));

$fb_user = $facebook->getUser();

if ($fb_user) {
    try
    {
       $me = $facebook->api('/me');
       $uid = $facebook->getUser();
    }
      catch (FacebookApiException $e)
    {
       //echo error_log($e);
       $fb_user = null;
    }
}

/* CALLBACK */
$result = array();

if ($fb_user) {
    $result['error'] = 0;
    $result['message'] = $me['first_name'];;
} else {
    $result['error'] = 1;
    $result['message'] = 'error';
}

echo json_encode($result);
?>
  • 写回答

1条回答 默认 最新

  • douyouming9180 2013-01-10 15:49
    关注

    Sorry, but it's not superfluous, I really need it to check things in database. In fact, if the user is not registered in database, the user is redirected to another page instead reloading the index page

    So, as I suspected, no real need for the AJAX call.

    You could just as well reload your index.php, do your database checks there, and then either put out content for a successfully logged in user, or redirect them from there using a Location header.

    Anyway, I need to understand why I can't retrieve my FB infos by reloading dynamically instead manually. This is the real problem.

    Well then you should investigate your real problem: Debug the exception you might be getting, or check what differences there are in the login flow using that extra AJAX step or avoiding it (like what cookies get set when, do they get send back with the next request, etc.)

    评论

报告相同问题?

悬赏问题

  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计