1

how to pass variable from zf to javascript/jquery?

thanks

4

6 Answers 6

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

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

3 Comments

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... <?php $this->inlineScript()->captureStart("PREPEND", $type = 'text/javascript', $attrs = ["nonce" => "r@nd0m"]) ?>
Also tried, $this->inlineScript()->captureStart("PREPEND", 'text/javascript', ["nonce" => "r@nd0m"])
Ugh. It looks like defining captureStart params might only exist for headScripts. That is just silly.
2
<?php
$this->view->foo = $foo;
?>

In your view:

<script type="text/javascript">
var foo = <?=Zend_Json::encode($this->foo)?>;
</script>

3 Comments

i want to pass variable to a js file
you can use this variable in your js file, as long as this code is executed before your js file is included
I would extract the variable to keep the js clean. In controller: $this->view->headScript()->appendScript('var_foo='.$foo); and js: var foo = _foo.
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.

3 Comments

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.
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.
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.
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.

2 Comments

how to get $message in js file, i got error undefined variable when i try use in $message in js file
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.
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.

Comments

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.

Comments

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.