1

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?

2
  • 1
    because there is no echo in JavaScript.... Commented Jul 16, 2015 at 1:21
  • Additionally, it is invalid HTML to have output before the DOCTYPE. Commented Jul 16, 2015 at 1:30

2 Answers 2

3

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>
Sign up to request clarification or add additional context in comments.

Comments

0

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>";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.