且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Facebook的API和放大器; Ajax的POST请求

更新时间:2023-01-23 19:21:19

  

抱歉,但它不是多余的,我真的需要它来检查的东西在数据库中。事实上,如果用户没有在数据库中注册的用户将被重定向到另一个页面,而不是重新加载索引页面

所以,我怀疑,没有真正的需要AJAX调用。

您也可以同样刷新你的的index.php ,做你的数据库检查那里,然后要么放出来的内容为成功登录的用户,或重定向他们有使用的位置的头。

  

不管怎样,我需要了解我为什么不能动态地重新加载,而不是手动检索我的FB的相关信息。这是真正的问题。

那么,你应该调查你的真正的问题:调试异常,你可能会得到,或检查有什么不同使用额外的AJAX一步都在登录流程或避免它(如得到什么饼干设置时,他们得到发回的下一个请求,等等。)

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);
?>

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.)