1

how to pass variable from zf to javascript/jquery?

thanks

user1400
  • 1,411
  • 4
  • 26
  • 36
  • 2
    Unless you refine your question to address a specific issue, this is done the same way as http://stackoverflow.com/questions/392470/passing-value-to-javascript-from-php and there is also a number of View Helpers for jQuery: http://framework.zend.com/manual/en/zendx.jquery.html – Gordon Apr 10 '10 at 09:43
  • At what event you want to pass a variable to javascript function ? – Naveed Apr 10 '10 at 10:08
  • 1
    Always keep this in mind: http://stackoverflow.com/questions/2034501/how-does-php-work – Felix Kling Apr 10 '10 at 10:18
  • why do you need php for that? – chelmertz Apr 10 '10 at 10:21

6 Answers6

6

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
  • 5,084
  • 3
  • 28
  • 51
  • Anyone have any idea how to add attributes to the script that gets created useing this? Based on what I could make from the docs, it would be something like the following but it doesn't seem to render... inlineScript()->captureStart("PREPEND", $type = 'text/javascript', $attrs = ["nonce" => "r@nd0m"]) ?> – Adam Youngers May 12 '21 at 21:38
  • Also tried, $this->inlineScript()->captureStart("PREPEND", 'text/javascript', ["nonce" => "r@nd0m"]) – Adam Youngers May 12 '21 at 21:41
  • Ugh. It looks like defining captureStart params might only exist for headScripts. That is just silly. – Adam Youngers May 12 '21 at 21:58
2

I know this is an old question, but I'm sure others could benefit from this:

You could use this extended HeadScript class and pass variables to JavaScript from a controller like this:

$this->view->headScript()->appendVar('dogName', 'Rocky')
                         ->appendVar('dogPictures', $pictures);

prependVar, setVar and offsetSetVar are also available for convenience' sake.

Bogdan Ghervan
  • 191
  • 3
  • 9
  • Hey Bogdan, I'm trying to use this but I get "Fatal error: Class 'Application\View\Helper\HeadScript' not found in /var/www/xxxx/zf2/2.2.2/library/Zend/ServiceManager/AbstractPluginManager.php on line 170". I feel like it's a setup problem, but I have HeadScript pointing to Application\View\Helper\HeadScript in getViewHelperConfig of my Application Module class. Also, I had to change the declaration to class Application_View_Helper_HeadScript extends HeadScript to get rid of the error that it couldn't find Zend\View\Helper\HeadScript. Kind of a newbie, not sure what to do next. – mutatron Aug 30 '13 at 20:43
  • Finally got it to load using autoload_classmap.php, but then it said "prependVar" method does not exist. I give up on that then. Just use the method of declaring javascript variables in my view, then appending the javascript file. – mutatron Sep 03 '13 at 16:27
  • I'm sorry for the trouble, @mutatron. This class is not compatible with Zend Framework 2. For anyone still using Zend Framework 1, I've added [proper installation steps](https://github.com/bogdanghervan/zf-append-var). – Bogdan Ghervan Jan 27 '15 at 01:06
2
<?php
$this->view->foo = $foo;
?>

In your view:

<script type="text/javascript">
var foo = <?=Zend_Json::encode($this->foo)?>;
</script>
I.devries
  • 8,747
  • 1
  • 27
  • 29
1

I know this will be late answer, And I have used @chelmertz solution, but currently I got some issue with that. I am working in an complex UI application and I needed lots of php arrays and other json objects in my external javascript files. And inclusion of my js scripts was not uniform, So each time if I need some thing from php to javascript I have to check whole things like ....

1) Am I placing appendScript() at correct position so the some.js script will find my variables defined

2) generated string which will be passed to appendScript() is a valid js syntax. and lot more ...

There is another way I have developed for Zend Framework specially. I have written a detailed tutorial here http://rupeshpatel.wordpress.com/2012/09/21/add-json-objects-arrays-and-variables-from-php-to-javascript/

summary:

1) create a common view file enclosed within tag, which checks for a property(an Array) let say $this->jsVars of a view object and defines js variables
code of this view file

<script>
<?php if(!empty($this->jsVars)){ ?>

<?php
foreach($this->jsVars as $var) {
if($var['type'] == 'json'){
?>
var <?php echo $var['name']?> = JSON.parse('<?php echo $var['value'];?>');
<?php } elseif($var['type'] == 'text'){ ?>
var <?php echo $var['name']?> = "<?php echo $var['value'];?>";
<?php }else{?>
var <?php echo $var['name']?> = <?php echo $var['value'];?>;
<?php
}}?>

<?php }?>

</script>

2) render this view in your layout file before echo $this->headScript() so all external scripts will have those js variables

<?php
echo $this->render('index/include_js_vars.phtml'); // rendering view

                $this->headScript()->prependFile(JS_BASE_URL.'/jquery-1.7.2.min.js');
$this->headScript()->appendFile(JS_BASE_URL.'/jquery.blockUI.js');
$this->headScript()->appendFile(JS_BASE_URL.'/commonJS.js');
$this->headScript()->appendFile('http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js');

                echo $this->headScript();
?>

3) append php arrays or json objects to $this->view->jsVars like

// in your action method

$test = array('mango','orange','banana');
$this->view->jsVars[] = array('name'=>'test','type'=>'json','value'=>json_encode($test));

now test will be defined in any of your script files as an array, No matter at what instance you have included your js file.

Rupesh Patel
  • 3,015
  • 5
  • 28
  • 49
1
<?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
  • 20,399
  • 5
  • 40
  • 46
  • how to get $message in js file, i got error undefined variable when i try use in $message in js file – user1400 Apr 10 '10 at 10:29
  • 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 Apr 10 '10 at 10:33
0

I came here and tried all the answers but non of them helped me, so what I ended up doing was the next (maybe it's too late, but could be helpful for someone else):

Inside the controller where you want to pass the variable to js:

public function someAction()
{
    $var = array(
        'test' => 'phpVar',
        'test2' => 'phpVar2'
    );

    $this->view->jsVar = $var;
}

Now in your layout, inside head tag, and before load any other script do this:

$this->headScript()->appendScript('var phpVars='.json_encode($this->jsVar));

Finally in your js file, you would be able to access the variable phpVars:

console.log(phpVars);

you could see in the console:

Object {test: "phpVar", test2: "phpVar2"}

being able to access each variable like phpVars.test and phpVars.test2

Now you can pass variables from your controller to js files everytime you want.

Chema
  • 29
  • 3