You should use the first method, although I recommend against the use
of <?= because it is deprecated in PHP5.3 and will be removed in PHP6.
I usually do it like this:
<script type="text/javascript">
(function(){
this.Config = <?php echo json_encode(array(...)); ?>
})();
</script>
which creates a global variable "Config".
On Aug 2, 1:14 pm, Michal Charemza <[email protected]> wrote:
> Hi,
>
> I'm trying to figure out a nice way of sending variables from the
> server (in my case PHP), to JS. I wonder what people think the best
> way is? I have thought of 1 1/2 methods :-) :
>
> 1a. Print out the variable using PHP in the global scope (window), to
> then be used in JS below the call:
>
> <script>var myJSVar = <?= $myPhpVar ?>;</script>
>
> 1b. Print out the variable in some function within the generated HTML
> page, say in a domready handler to be used in something
>
> <script>
> window.addEvent('domready', function() {
> var myJSVar = <?= $myPhpVar ?> <?= $myPhpVar ?>;
> new someClass({someOption: myJSVar});}
>
> </script>
>
> 2. Set the value as a cookie on the server, and read it using the
> MooTools Cookie object. I like this method as it avoids any "generated
> Javascript", which feels a bit messy.
>
> I guess this isn't that MooTools specific, but I wonder what people
> here think...?
>
> Michal.