Reputation: 158
i need to pass an array from my zend action to the view, possibly by using ajax, which is yet to be decided. in order to do that, i need to insert a script element and inside it define javascript variable, to which i will then pass my php array to, but i'm having trouble inserting script element into a zend_form. what is the easiest way to include this code into my phtml script:
<script type="text/javascript">
var obj = <?php echo json_encode($php_array); ?>;
</script>
Upvotes: 0
Views: 205
Reputation: 11217
RockyFord's solution is overly complex IMO. Just assign the PHP array to any view variable and add the code you posted (modified to use view variable) to the end of the view script - just after echoing the form.
//controller
$this->view->php_array = array(...);
//view
echo $this->form;
<script type="text/javascript">
var obj = <?php echo json_encode($this->php_array); ?>;
</script>
It will work as you expect.
Using JSON view helper is not ideal to use beacuse it modifies the headers and also disables layout by default. You can replace json_encode
with Zend_Json::encode
to make it work even without json_extension loaded in PHP.
Upvotes: 0
Reputation: 8519
You can use the view helper inlineScript() to pass java script to your view.
in your action $this->inlineScript()->setScript('java script here');
echo this out in your view <?php echo $this->inlineScript() ?>
you can also use the json() helper to pass json to the java script in your view.
Upvotes: 1