Reputation: 133
I am passing a PHP variable to Javascript, but only at a specific point in the code. As the PHP code continues, the variable I need changes. I could easily just run the Javascript and grab the PHP variable when the page is done loading, but that won't pass the information I want. I want the Javascript to grab the PHP variable at that point, and then ignore subsequent changes to it.
The actual program I'm working with is several thousand lines of code, so I created a simple page to mess around with this issue. The code below shows what I'm trying to do.
<?php
$php_var = 'something';
if(true) {
$php_var = 'new';
echo '
<script type="text/javascript">
js_var="<?php echo $php_var; ?>";
alert(js_var);
</script>
';
}
$php_var = 'later changes';
?>
<script type="text/javascript">
var js_var;
</script>
This doesn't work, however. js_var is set when the inline script is run, but it is just set to a string that says <?php echo $php_var; ?>
rather than actually evaluating it.
Upvotes: 3
Views: 394
Reputation: 1174
$php_var = "foo";
echo '
<script>
var js_var = '. json_encode($php_var) .';
alert(js_var);
</script>
';
Produces:
<script>
var js_var = "foo";
alert(js_var);
</script>
Upvotes: 1
Reputation: 324820
PHP runs first, and whatever JS is sent to the browser is run. I think you just want this:
echo '<script type="text/javascript">
js_var = '.json_encode($php_var).';
alert(js_var);
</script>';
Upvotes: 2