0

Actually I want to define a json variable in my controller and access it in my js file.
I used to do it in yii framework like below:

Yii::app()->clientScript->registerScript('helpers', '                                                           
        yii= {                                                                                                     
           test: 'test'                                                                                                       
       };                                                                                                          
   ',CClientScript::POS_HEAD);

And I can access it like yii.test in js file.
For some reason I don't want to declare it directly in view header or footer part.
Thanks in advance

1 Answer 1

2

You could build an endpoint for that and load it via AJAX. Otherwise, printing it somewhere in the page (preferrably in <head>) is pretty much the only way to do pass in values from the server to JS.

Additionally, I would discourage writing JSON or JS objects manually in PHP. I suggest you create a PHP array/associative array representing that object and use json_encode to turn it into a string. You can then print it on the page or send down via AJAX.

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

7 Comments

Thanks a lot, I would wait for any other answer, and mark this as correct if better one didn't come. But I'll appreciate you if tell me the reason of discourageness of doing this. Is that because separation of concerns?
@HosseinShahsahebi because you can write malformed objects or fumble with quotes.
In practice I have some problems. If I want to access the global variables which loaded through AJAX, AJAX call must be synchronous in top level of my page and it will effect user's experience. Am I correct? Do you have any suggestion? By the way sorry, I don't know why I can't mention you.
@HosseinShahsahebi If you do the AJAX, it doesn't need to be a global and it doesn't need to be in head. However, code that needs the values need to be executed in a function called after the callback returns.
@HosseinShahsahebi Depends on the case. If they're too small, just print them in the head instead. If they're a bunch of utility data, you can bundle them up in one AJAX call. If each are qualified resources, then they should exist as restful endpoints each. There's no hard rule, it's just a guideline.
|

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.