Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass PHP variable to Javascript at a specific point

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.

like image 255
Steve Avatar asked Sep 29 '26 09:09

Steve


1 Answers

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>';
like image 102
Niet the Dark Absol Avatar answered Sep 30 '26 22:09

Niet the Dark Absol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!