I am having a problem with a simple php file in which I am trying to pass a variable from php to javascript. I have used the exact same code successfully in a more complex program, but cannot get it to work in the most trivial context here. Below is the entire code. When I run it, it complains that xxx is an unidentified variable:
<?php
echo "<h2 style='text-align: center'>Welcome</h2><br>";
echo '<script>var xxx = "Hello";</script>'
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<script>
echo xxx;
</script>
</body>
</html>
I know there are other ways to pass data from php to js, but this one is simplest and I have used it before. Why is it failing here?
-
1because there is no echo in JavaScript....epascarello– epascarello2015年07月16日 01:21:49 +00:00Commented Jul 16, 2015 at 1:21
-
Additionally, it is invalid HTML to have output before the DOCTYPE.Khalos– Khalos2015年07月16日 01:30:23 +00:00Commented Jul 16, 2015 at 1:30
2 Answers 2
You are mixing php and JavaScript syntax
<script>
echo xxx;
</script>
needs to be
<script>
console.log(xxx);
</script>
ANd the php code should be in the body if you are outputting HTML.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<?php
echo "<h2 style='text-align: center'>Welcome</h2><br>";
echo '<script>var xxx = "Hello";</script>'
?>
<script>
console.log(xxx);
</script>
</body>
</html>
Comments
This is how you can pass the value. Use ID as the parameter.
<script>
window.onload = function () {
document.getElementById('NO').onchange = disablefield;
document.getElementById('YES').onchange = disablefield;
}</script>
echo "<tr><td width='50%'><input type='radio' name='item' value='A' id='YES'>YES</td><td><input type='radio' name='item' value='B' id='NO'>NO</td></tr>";