user3670475
user3670475

Reputation: 3

Using a PHP variable inside JavaScript

I'm pretty new, so go easy. I am using a session in PHP with a few variables. I want to concatenate two strings together from my PHP session when the clicks a button. I am using JavaScript onclick to try and achieve this.

I am having trouble getting my JavaScript to accept my PHP variables. Does anybody have any suggestions?

PHP:

$_SESSION['user1'] = $_POST['user'];
$_SESSION['string3'] = $_POST['string1'];
$_SESSION['string4'] = $_POST['string2'];

echo $_SESSION['user1'];
echo $_SESSION['string3'];
echo $_SESSION['string4'];

if(isset($_SESSION['user1'])) {
    echo 'Welcome, '.$_SESSION['user1'].". Lets concatenate ".$_SESSION['string3']." and ".$_SESSION['string4'];

} else {
    echo "<meta http-equiv=\"refresh\" content=\"0;URL=">";
}


<button onclick="xy()">Try it</button>
<p id="answer"></p>

JS:

<script type="text/javascript">
function xy() {
    var x = "<?php $_SESSION['string3']; ?>";
    var y = "<?php $_SESSION['string4']; ?>";
    document.getElementById("answer").innerHTML = x + y;
}
</script>

Upvotes: 0

Views: 134

Answers (2)

Shomz
Shomz

Reputation: 37701

You need to echo the PHP variable there because otherwise they output nothing and the JS variable ends up empty:

var x = "<?php echo $_SESSION['string3']; ?>";
var y = "<?php echo $_SESSION['string4']; ?>";

So for example, if $_SESSION['string3'] is "abc", PHP will echo the value inside the JS and you'll get this:

var x = "abc";

instead of:

var x = ""; // no output from PHP when there's no echo

To simplify things, here is your whole function:

<script type="text/javascript">
function xy() {
    var x = "<?php echo $_SESSION['string3']; ?>";
    var y = "<?php echo $_SESSION['string4']; ?>";
    document.getElementById("answer").innerHTML = x + y;
}
</script>

Upvotes: 4

NoNeedInName
NoNeedInName

Reputation: 1

Maybe it should be something like this?

echo "<script type=\"text/javascript\">\n";
echo "function xy() {\n";
echo "var x = ".$_SESSION['string3']."\";\n";
echo "var y = ".$_SESSION['string4']."\";\n";
echo "document.getElementById(\"answer\").innerHTML = x + y;\n}";
echo "</script>";

Upvotes: 0

Related Questions