0

How does one set the javascript variable declared in cake php, for example

echo $this->Js->set('jsvalue','test');

I need to get the jsvalue value inside normal javascript

<script>
    // This will need to get value as 'test'
    console.info(jsvalue);
</script>

I am currently using cakephp (1.3). If this feature is not supported in version 1.3, please show me how it is implemented in version 2.0.

2 Answers 2

1

It's set on window.app as an object to namespace it. Or, setting $setVariable on your JsHelper properties will change the namespace, to window.<namespace>.

So, it will be set like this:

window.app = {"jsvalue" : "test"}

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

8 Comments

So, how it can be taken in normal javascript as an variable. While I tried to take it as window.app.jsvalue gives an error window.app is undefined.
I think it might be setting to something other than 'app', perhaps your app name? Try window.<app_name> instead.
My app folder name is 'app' itself. When i checked in firebug inside script cdata window.app = {"jsvalue":"test"}.but how it can retrevied...
It's just an object, so window.app.jsvalue = 'test'.
While tried with above gives undefined error. console.info(window.app.jsvalue) gives error
|
1

If you have written javascript in the view part then directly you can use something like this. I'm not getting what is $this->Js->set('jsvalue','test'); instead of this if you use normal $this->set('jsvalue','test'); and use it as below it should work.

<script>
    // This will need to get value as 'test'
    console.info(<?php echo $jsvalue; ?>);
</script>

Try this, this should do.

3 Comments

It should work, I think this is the only way to do it. Check the source code, check if the PHP value is actually set and check firebug for javascript errors.
@KevinVandenborne The firebug error is syntax error and cake error Undefined variable: jsvalue
Sorry I forgot to add $ symbol before jsvalue variable. I'm editing my answer. You can try now, but make sure you've set that value from controller as other variable. Like this you can use any variable in the javascript.

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.