I'm trying to mix php and javascript, because my javascript needs to access some php variables when the page loads. I'm having trouble understanding something, and I've made a code example.
<?php
session_start();
$test = 100;
$_SESSION['test'] = 200;
?>
<html>
<head>
<title>Test This Out</title>
</head>
<body>
<h1> Testing Javascript and PHP Mixed </h1>
<p>
<?php
echo("The value of \$test is $test and the value of \$_SESSION['test'] is ");
?>
</p>
<p>
<script type="text/javascript">
<?php
session_start();
if(isset($test)) echo("document.write('Non-session variable exists and is $test <br />');");
else echo("document.write('Non-session variable does not exist<br />');");
if(isset($_SESSION['test'])) echo("document.write('Session variable exists <br />');");
else echo("document.write('Session variable does not exist<br />');");
?>
</script>
</p>
</body>
</html>
Output looks like:
Testing Javascript and PHP Mixed
The value of $test is 100 and the value of $_SESSION['test'] is
Non-session variable exists and is 100
Session variable exists
So I'm trying to understand what types of php variables are available to the script. It appears that the variable I've called $test is available, but even though it knows that
$_SESSION['test']
exists, if I try to output this value (in the exact same way I output the
$test
variable), the whole system hangs.
My questions are: 1. Can the php used in the javascript "see" variables I've defined earlier on in the page? 2. Why is my attempting to print the
$_SESSION['test']
variable making the whole thing crash (nothing at all is rendered)? 3. Is the second
session_start(),
the one in the script, necessary?
Thanks for any help.