Help please: Passing PHP values to Javascript

Discussion in 'PHP' started by Houer, Jun 25, 2008.

  1. #1
    Hi,

    I need to pass some PHP values to Javascript. I tried the following example:

    <? $vartopass = "Hello"; ?>
    <script = "javascript">
    var strnewVar = '<?=$vartopass?>';
    alert(strnewVar);
    </script>

    But the screen output is "<?=$vartopass?>" instead of "Hello".
    What's wrong with my code? How to make it work?

    Thanks a lot for any help.
     
    Houer, Jun 25, 2008 IP
  2. Danltn

    Danltn Well-Known Member

    Messages:
    679
    Likes Received:
    36
    Best Answers:
    0
    Trophy Points:
    120
    #2
    Perhaps you don't have PHP short tags on (I'm assuming this is in a PHP script.)

    Try:
    <?php echo $vartopass; ?>
     
    Danltn, Jun 25, 2008 IP
  3. Houer

    Houer Peon

    Messages:
    2
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thank you Danltn for the reply.
    I tried your code, but the alert didn't show at all this time. Do you know what the reason probably is?

    Thank you very much.
     
    Houer, Jun 25, 2008 IP
  4. J.T.D.

    J.T.D. Peon

    Messages:
    86
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Is the file extension .php?

    - JTD
     
    J.T.D., Jun 25, 2008 IP
  5. Danltn

    Danltn Well-Known Member

    Messages:
    679
    Likes Received:
    36
    Best Answers:
    0
    Trophy Points:
    120
    #5
    <script = "javascript">
    var strnewVar = '<?=$vartopass?>';
    alert(strnewVar);
    </script>

    Should be...
    <script type="text/javascript">
    ...
    </script>
     
    Danltn, Jun 25, 2008 IP