0

In my cakephp2 app I'm trying to pass a variable from my layout to Javascript.

I'm using the following code:

$test = array('a'=>'test');
$this->Js->set('data', json_encode($test));
echo $this->Js->writeBuffer();

Which results in the following HTML:

<script type="text/javascript">
//<![CDATA[
$(document).ready(function () {window.app = {"data":"{\"a\":\"test\"}"};});
//]]>
</script>

However when I try to reach window.app in my chrome console, I get the error "window.app is undefined".

Any ideas what I'm doing wrong?

1 Answer 1

1

JavaScript variable was set on document ready which you can't access globally so set onDomReady to false to access globally.

    $test = array('a'=>'test');
    $this->Js->set('data', json_encode($test));
    echo $this->Js->writeBuffer(array('onDomReady' => false));

Hope this helps you.

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

3 Comments

Unfortunately that gives the same result "window.app is undefined".
But shouldn't I be able to see window.app in my chrome/firebug console? Because there it can't be reached.
My bad, it works perfectly now. array('onDomReady' => false) did the trick. Thanks!

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.