开发者

assign a php value from a script value

I have some code

<script>

            FB.Event.subscribe('auth.login', function(res开发者_JS百科ponse) 
        {

            FB.api('/me', function(response) {
      alert(response.id);

    });
</script>

An alert screen appears and shows the value i want (response id). but i would like to assign this value to a php value called $id i know how to do this but because the value is in script it wont work, i have tried adding in the below code without success

</script>  <?php $id ?> <script> response.id </script> <?php ; ?> <script>

this code is added just below the alert(response.id);


If you want to use the value on the server side the only way is to send it with AJAX to the server and after that store it in the Database or do something.

You can do something like this

<script>

    FB.Event.subscribe('auth.login', function(response) 
    {

        FB.api('/me', function(response) {
           $.ajax({ type: "POST", url: "save-fb-id.php",data: {id: response.id} });
        }

    });
</script>

Forgot to mention this is jQuery implementation

In your PHP script do the following:

<?php
    $fbID = $_POST['id'];

    save_to_db($fbID);
?>


PHP code is executed by the server before it sends the page to the client. Anything in a script tag is executed by the client. In order to send a value back to PHP, you'll have to submit some kind of request back to the server - it could be a hyperlink (a href='page.php?id=whatever), a form with a hidden value, an ajax request, etc

To add the value to a database, you'll need a php page (eg mypage.php) to insert your entry, with something like

if (isset($_GET['insertme'])) {
  mysql_query("INSERT INTO myidtable (id) VALUES ('{$_GET['insertme']}')");
}

And in your script, find some kind of ajax function and send a request to mypage.php?insertme=myid, where mypage is your database inserting page and myid is the id you want to insert.

Note that it's unsafe to insert values from $_GET directly into your database like that - you'll want to filter out single quotes first to prevent sql injection.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜