views:

407

answers:

4

hello all

how to pass variable from zf to javascript/jquery?

thanks

A: 
<?php
$this->view->foo = $foo;
?>

In your view:

<script type="text/javascript">
var foo = <?=Zend_Json::encode($this->foo)?>;
</script>
I.devries
i want to pass variable to a js file
user1400
you can use this variable in your js file, as long as this code is executed before your js file is included
I.devries
I would extract the variable to keep the js clean. In controller: `$this->view->headScript()->appendScript('var_foo='.$foo);` and js: `var foo = _foo`.
chelmertz
+1  A: 
<?php

class SomeController extends Zend_Controller_Action {
    public function indexAction() {
        // a file
        $this->view->headScript()->appendFile('yourJsFile.js');
        // inline script
        $message = 'hello!';
        $this->view->headScript()->appendScript("jQuery(function(){alert('$message');});");
    }
}

This requires that you add echo $this->headScript() to your view- or layout-script.

chelmertz
how to get $message in js file, i got error undefined variable when i try use in $message in js file
user1400
You aren't supposed to use `$message` in your JS, it's a PHP variable which gets parsed by PHP before being inserted into plain JS.
chelmertz
A: 

If you want pass a variable to javascript function on any click event then here is the solution:

// link
<a href="#" onclick=myfunc( $this->myvalue ) >My Link</a>

// submit button
<input type=submit onclick=myfunc( $this->value ) />

<script type='text/javascript'>
  function myfunc( value ) {  
    alert( value  );
  }
</script>
NAVEED
+2  A: 

you can create your javascript dynamicly by useing Headscript View Helper it had function like :

<?php $this->headScript()->captureStart() ?>
var action = '<?php echo $this->baseUrl ?>';
$('foo_form').action = action;
<?php $this->headScript()->captureEnd() ?>

Source : ZF documentation

tawfekov