Search code examples
javascriptstandardsunobtrusive-javascript

Correct way to pass a variable from the server backend to javascript?


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?


Solution

  • 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](http://en.wikipedia.org/wiki/Ajax_(programming)).