Using jQuery with Yii

Yii is a high performance PHP framework, which has all sort of weapon to build up your efficient web application. Most popular javascript library jQuery are already included with the core of this framework, so for using jQuery no one need to included it.

For register jQuery as core of your application just need to add one line code in main view file.

clientScript->registerCoreScript('jquery'); ?>

With yii default settings, this file can be found in ‘protectedviewslayouts’ directory. Under this directory find main.php and put those code into HEAD section.

Normally we use jquery in a script tag like that:

$(document).ready(function(){
	alert('hello world');
});

In Yii we can use jquery within our php code. like that:

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

Here, ‘testscript’ parameter are nothing just a name of your script which need to be unique in a view file. POS_READY is identical to $(document).ready(). You can use POS_HEAD to put your script in head section. This way of using jquery will automatically prevent conflict of several javascript in your application