0

I have a config file in PHP.

return array(
'window_width'      => 1000,
'window_height'     => 800
    //etc
);

How can I read these vars into my javascript? Should I echo them to the page, in perhaps a data attribute and pick them up from there? Or is there a better way?

panthro
  • 22,779
  • 66
  • 183
  • 324

3 Answers3

2
<script>
   var settings = <?php echo json_encode($your_array); ?>;
   alert(settings.window_width);
</script>
Marc B
  • 356,200
  • 43
  • 426
  • 500
  • I would have hoped a 187k rep user like you would have gone searching for the obvious dupe, rather than the easy rep points. – Matt Jun 16 '14 at 16:52
  • because searching for the dupes takes longer than actually typing out that code sample. – Marc B Jun 16 '14 at 16:54
0

Echo them directly where you need them in javascript. You can echo a javascript object to reflect the data structure. Something like this should work:

var x = <?php echo '{window_width:"1000", window_height:"800"}'; ?>;
hanleyhansen
  • 6,304
  • 8
  • 37
  • 73
0

No. You should echo them to the page.

PHP runs on server, but JavaScript on client machine, browser. In PHP you should echo something like this:

<?php
echo('<script>var myvar = '.$myvar.';</script>');
?>
tensojka
  • 302
  • 1
  • 5
  • 20