0

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>
2
  • 1
    I don't know why you'd want to, but you can't add javascript to a form. Just send the javascript over to the view and echo the js out after the form Commented May 18, 2012 at 13:30
  • you can't just echo in js, it won't be executed Commented May 18, 2012 at 14:30

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thanx. i just found that too. it's kind of a simple thing, but it took me a looong time to google it. thanx again for your help
0

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.

2 Comments

This is a great solution for when you need to do it just once.
You're right. If you need to use the code in multiple places, it's ideal to move it to extenal JS and link it using appendScript($filename)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.