views:

156

answers:

3

I need to pass a variable that php is aware of to my javascript code and I'm wondering what the correct way to do this is.

I already know that I could add this to the page generation:

<script type="text/javascript">
var someJSVariable = <?php echo $somePHPVariable ?>
</script>

But I find this method to be more obtrusive than I'd like. I am wondering if there is a better way to do this, or am I stuck with having to just inject inline javascript code in to the view script?

+1  A: 

I love json_encode() for this kind of thing.

But yes, you are "stuck" with this inline approach. Honestly, would you prefer this?

$js = '<script type="text/javascript">';
$js .= "var someJSVariable = " . $somePHPVariable;
$js .= '</script>';

// some time later
echo $js;

Didn't think so. The inline approach is php's bread and butter. Go with it.

Crescent Fresh
+3  A: 

If it's just 1 variable, I think this is the best solution. If you don't want to mix in JS into your normal view, make a separate view which will be rendered as .js file and then just include a link to that .js in your "real" view. If you need performance, some smart catching would be needed there.

If there's more then 1 variable, for example a data exchange between html document and server you could use AJAX.

Maiku Mori
A: 

You can always make an asynchronous request to a separate URL to get the dynamic value. But, you will take a slight performance penalty there as the page loads. With that in mind, I would recommend the in-line method you outlined.

You could also include another "js" file that's really a PHP page that's generating a bunch of javascript constants that you can then access in your main page.

Chase Seibert