0

I'm trying to pass a variable array to Javascript in CakePHP 2.3, but can't get it to work. I hope someone has a good solution to this.

I have successfully passed the array to my view by placing the following in the controller:

$this->set(compact('myArray'));

And tried this in my view to pass the variable through to myJs.js.

$this->Js->set('myArray');
$this->Html->script('myJs');

Why can't I access the myArray in myJs.js?

2 Answers 2

4

Passing a varible to javascript by using the methods of Js helper

Just set the variable you want to set using set method of js helper.

$this->Js->set('myArray', $myArray);
echo $this->Js->writeBuffer(array('onDomReady' => false));

and you can access the $myArray variable as window.app.myArray your javascript.

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

5 Comments

let me know if you've any query or concern @Hans .
This way I'm getting an error "window.app is undefined". Any ideas?
check in your view-source whether this variable is set or not
It would be better to specify onDomReady to false to prevent the error "window.app" is undefined. Also, looks like inline is not necessary as well. So my version is: echo $this->Js->writeBuffer(array('onDomReady' => false));
I just set inline to false to show the script at the top of page. I've edited answer for setting onDomReady to false Thanks for the info. @VCD
1
echo $this->Html->scriptBlock(
    "var myArray = '" . json_encode($myArray) . "'",
    array('inline' => true)
    );
echo $this->Html->script('myJs');

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.