QLands
QLands

Reputation: 2586

How to read PHP variable from JavaScript?

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?

Upvotes: 3

Views: 17227

Answers (5)

T.J. Crowder
T.J. Crowder

Reputation: 1074148

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) ?>;

Upvotes: 4

davidethell
davidethell

Reputation: 12018

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.

Upvotes: 1

errkk
errkk

Reputation: 305

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);?>

Upvotes: 1

No Results Found
No Results Found

Reputation: 102735

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

Upvotes: 6

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

try:

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

Upvotes: 0

Related Questions