Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the proper way to add javascript inside jQuery's $(document).ready with Yii

Tags:

jquery

yii

I'm using Yii framework. On a couple of pages I want to add some custom UI stuff using jQuery. I want the result to be something like:

$(document).ready(function() {
     ... my code
});

I found advice to use something like this:

Yii::app()->clientScript->registerScript('testscript',"
    alert('hello world');
",CClientScript::POS_READY);

However, I have a rather large javascript code (about 100 lines) and it's hard to even read it when it's inside PHP string (no syntax highlighting in editor, no code folding).

There must be some better way to do it?

I wouldn't mind even placing the code in separate .js file, but I have no clue how to load it in to document.ready handler?

like image 471
Milan Babuškov Avatar asked Jan 30 '26 22:01

Milan Babuškov


2 Answers

Isolate your code into a class/function in a JS file, register that with registerScriptFile, then invoke that class / method with registerScript (will then be added to the ready-method which CClientScript uses.

like image 83
Eirik Hoem Avatar answered Feb 02 '26 16:02

Eirik Hoem


Well, I've never used yii, but searching around on Google I've found that you can add javascript to yii.

I'm a .net guy, but this link may help you out. http://www.yiiframework.com/forum/index.php?/topic/4778-what-is-the-best-form-to-load-jquery/

I'm just guessing but it'll probably look like this...

 Yii::app()->clientScript->registerScriptFile('/myScript.js');

And in myScript.js you'd write...

 $(document).ready(function() {
    alert('hi'); 
    //js code goes here
 });

Now I'm just guessing, but you'd probably have to include the jquery plugin before any of this. So, its probably something like ...

(PHP)

<?php Yii::app()->clientScript->registerCoreScript('jquery'); ?>
<?php Yii::app()->clientScript->registerScriptFile('/myScript.js'); ?>

(JQuery)

$(document).ready(function() {
    alert('hi'); //script goes here
 });
like image 21
sreyaNotfilc Avatar answered Feb 02 '26 16:02

sreyaNotfilc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!