3

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.

1
  • that's because the <?php echo $php; ?> is extra and single quote strings don't process variables. try echo ("<script>js_var=$phpvar;alert(js_var);</script>"); Commented Mar 27, 2013 at 1:05

2 Answers 2

2

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>';
Sign up to request clarification or add additional context in comments.

1 Comment

Yep. That does it. Thanks!
1
$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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.