0

I have a Javascript variable screenName for twitter users. When they connect to my site, I want a php script to write their name in a txt file. How could I do this. I looked into writing files with AJAX but no luck.

<script type="text/javascript">

twttr.anywhere(function (T) {
    var currentUser,
        screenName,
        profileImage,
        profileImageTag;
    if (T.isConnected()) {
        currentUser = T.currentUser;
        screenName = currentUser.data('screen_name');
        $('#twitter-connect-placeholder').append("<p style='color:white;text-shadow:none;'>Howdy " +" " + screenName + "!");
        var screenName = "<?= $js ?>";
    } 
});
</script>

<?php
$check = $_GET['track'];


if ($check == '1') {
    $fp = fopen('data.txt', 'a');
    fwrite($fp, "{$js}");
    fclose($fp);
}
?>

If you view the source screenName equals ""

Any ideas on this?

MaxArt
  • 22,200
  • 10
  • 82
  • 81
Ben Thomson
  • 558
  • 3
  • 8
  • 25

1 Answers1

1

In order to approach the problem, you'll need to understand that the PHP is executed on the server side, before the page is sent to the user, and the Javascript is executed on the client side, in the user's browser, i.e. after the PHP code. Obviously, you need the events to happen in the reverse order. An example implementation follows:

Using jQuery, you can do:

if (T.isConnected()) {
    var currentUser = T.currentUser;
    var screenName = currentUser.data('screen_name');
    $.post(
        '/writename.php',      // request url
        {'name' : screenName}, // POST data
        function() {           // optional callback
            alert("done!");
        }
    );
}

And, in your writename.php:

if ($_POST['name']) {
    $fp = fopen('data.txt', 'a');
    fwrite($fp, $_POST['name']);
    fclose($fp);
}
avramov
  • 2,119
  • 2
  • 18
  • 41
  • 2
    @BenThomson: Define "doesn't seem to be working." In what way is it not working? Is the value being included in the POST to the server? (You can check that with something like Firebug.) Is the server-side script getting the value from the `$_POST` array? Where is it failing? – David Jul 07 '12 at 08:56