Reputation: 3489
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.
Upvotes: 3
Views: 818
Reputation: 5127
There are so many ways of mixing up ur js with PHP. One thing you always keep in mind is
Your PHP is executed first in the server, before JS gets executed.
Looks like you are trying to dynamically add something to your selectbox. If that is the case you can do something like this
<?php
function createSelectbox( $selItems ) {
$selTxt = "<select>";
foreach ($selItems as $id => $value)
$selTxt .= "<option id='" .$id. "'>". $value. "</option>";
$selTxt .="</select>";
return $selTxt;
}
?>
<html>
<head> </head>
<body>
<?php
$selItems = Array( 1 => "One", 2 => "Two", 3=> "Three" );
echo createSelectbox($selItems);
?>
</body>
</html>
Upvotes: 1
Reputation: 30248
This is pretty horrible, a better way to do it is request the data over an Ajax request, in a suitable format (e.g. JSON)
To expand on why it's "horrible". Obviously this function was built in a quick-n-dirty fashion to get the job done, ongoing debugging and maintenance of the function is hampered by this approach. Separating out the delivery of server-side data and client side processing helps keep things simple and easier to trace.
Upvotes: 1
Reputation: 19315
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 arrays n
-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.
Upvotes: 3