Using a php variable with javascript?

Hi,

I'm following a book about php sessions. So I've set myself up to the point where a user on my system can login and is served a page that looks like this:

<?php

    session_start();
    $username = $HTTP_POST_VARS['username'];
    $password = $HTTP_POST_VARS['password'];
?>

Ok so that is great, now the page loads and knows the logged in username and password. I have some javascript functions that need to know the username though at some point:

<script>
    var strCurrUserName = $username;
    var vParams = strCurrUserName + "," + "something good";
    httpAjaxRequest.open("GET", url + vParams, true);
</script>

How can we do that?

Thanks
LVL 7
minnirokAsked:
Who is Participating?
 
RoonaanCommented:
hongjun:

date input: always validate;
data output: always escape;

-r-
0
 
RoonaanCommented:
var strCurrUserName = "<?php echo addslashes(htmlspecialchars($username)); ?>";

-r-
0
 
hongjunCommented:
alert("<?= $msg ?>");


var strCurrUserName = "<?=$username?>";
0
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

 
hongjunCommented:
sorry..

just this

var strCurrUserName = "<?=$username?>";
0
 
minnirokAuthor Commented:
that does it
0
 
minnirokAuthor Commented:
This question was for 500 points, may I ask one more related question that is also pretty simple? I'm using some AJAX in my script, but the php function I'm calling always returns an extra space character:

<?php
    echo "Hello!";
?>

<script>

function waitForAjaxResponse()
{
    if (httpResponse.readyState == 4) {
        alert("["  + httpResponse.text +  "]");  
    }
}

And the alert box always says:

    "[ Hello!]"

Any ideas why the heck I'm always getting that extra space character in there?

Thanks
</script>
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.