What is the best way to handle mixing PHP into Javascript? Should it not be done? Should it be done in a certain way? I am working on a project and I found the following javascript function:
function getStuff() {
<?php
$stuff = "0:Select";
foreach ($this->stuff as $k => $v){
$stuff = $stuff . ";" . $v['stuff_id'] . ":" . $v['stuff_name'];
}
?>
return "<?= $stuff ?>";
}
Assuming I need the data that the PHP is providing what is the ideal way to get it? This doesn’t seem like it to me but the person that wrote this is my boss so I want to ask before trying to change it.
FYI, this JS is used in a view script and the data for $this->stuff is passed in from the controller that uses it.
A great way to do it is to prepare the data into
JSON, and then make it a variable on the page. You can have complex structures (associative arrays full of arraysn-deep), and have that represented as an object literal in javascript.In general, you’re right to have an aversion to jumping in and out of PHP tags like that. It’s ugly and quite hard to read/maintain.