Passing PHP Data to Javascript Chris London
I don’t like mixing my languages together. Some might call it OCD but I think keeping them separate really helps the code be more extensible and maintainable. One of the most common language mixings comes from wanting to pass PHP data to Javascript. To me there are only two ways to do it.
1) Via Ajax. This is, probably, one of the most common ways to pass data from PHP to Javascript. I think there are a lot of benefits for passing data via Ajax but I think it should be avoided on page load. If you’re doing a bunch of computations on page load anyway, why pass a blank screen to the user to load data in later? Also if the user doesn’t have Javascript enabled then the site doesn’t work at all.
2) Indirect injection My preferred method for passing PHP data to Javascript is via indirect injection. A lot of developers I’ve worked with will use direct injection like this:
<script>
var id = <?= $id ?>;
</script>
But direct injection poses lots of problems for example if the variable is undefined PHP may throw a notice which the Javascript will interpret as a syntax error and all the Javascript below it will not be parsed/run. This method also prevents you from being able to put your Javascript in a separate file.
Indirect injection looks like this:
<div>
<?php foreach ($reports as $report) : ?>
<div data-id="<?= $report->id ?>">
<!-- ... -->
</div>
<?php endforeach; ?>
</div>
With this indirect method you can then retrieve the id from the HTML with jQuery like this: $('.report').attr('data-id')
Side note
Some people may argue well now you’re mixing PHP and HTML, you’re just moving the problem. To me, the problem there relies on PHP’s ability to be a templating language and that’s a whole different discussion.