How to read PHP variable from JavaScript?

15,778

Solution 1

Unless you have some configuration to allow it, .htm files won't execute PHP code, you'll have to use a .php file.

If you look at your HTML page source in the browser, you'll probably see all the PHP code.

The only other explanation is that short tags <? ?> aren't enabled, you'll have to use
<?php echo $var; ?>

Solution 2

But when I open the file with the browser the value of val is "" and not 'foo'

Sounds like you have shorttags disabled (and are using PHP < 5.4.0). Try

var val = "<?php echo $var ?>";

Edit: And note CM Kanode's comment on the question: If it's a .htm file, odds are that your server isn't running it through PHP at all (that would take special configuration and probably not be a good idea). (You are opening this via an http:// URL, right? Not opening the file locally? Because unless the PHP server gets involved, the PHP tags can't be processed.)


And better yet, let json_encode make sure the value is property quoted and such for you:

var val = <?php echo json_encode($var) ?>;

Solution 3

Maybe you don't have shorttags enabled, try

You might also want to look out for escaping of string and stuff, so if you have something more complex than a string, you could use JSON

<?php $var = array( 'stuff' => 'things' );?>

<?php echo json_encode($var);?>

Solution 4

Your post says that your file extension is .htm. Do you have your web server set to parse .htm files as PHP? If your server is only parsing .php files rename your file and try again as that would explain why the isn't being processed. If it is set to parse .htm files then T.J. Crowder's answer is the most likely issue.

Share:
15,778
QLands
Author by

QLands

Updated on June 15, 2022

Comments

  • QLands
    QLands almost 2 years

    I know that there are many questions about this but I cannot make it work.

    My HTML (test.htm) has only this code

    <?php
    $var = 'foo';
    ?>
    <script type="text/javascript" language="javascript">
    var val = "<?=$var?>";
    alert(val);
    </script>
    

    But when I open the file with the browser the value of val is "<?=$var?>" and not 'foo'

    How can I make it work?