Yii Framework – An Easy was to split Javascript from HTML

Using MVC pattern (which is a MUST for most of the frameworks) you can write Javascript in a View but this approach has many disadvantages such as problematic code obfuscation or quick assembling of entire project Javasctipt while transferring it to a separate server – all these will cause difficulties.

Today I would like to share the way we organize JS files for the project in our team.

Read More - http://weavora.com/blog/2011/11/24/yii-framework-an-easy-was-to-split-javascript-from-html/

Interesting. But how do you reuse js code if you have a single js file for every action (or i did not understand maybe)? And could you please show how would you pass php data to js?

Many thanks for sharing this :)

Mostly we organize reusable code into jQuery plugins. Sometime it would standalone js classes. That’s cover all our needs for now.

Here are few ways to put php data into js-action:

  1. define global data into html:


$.app.baseUrl = '...';

$.app.someVar = '...';

  1. setup delayed js-action:

// js-action for /user/index

function UserIndexAction() {}

UserIndexAction.prototype = {

    delayed: true, 

    init: function(properties) {

         var self = this;





// usage: /protected/views/user/index.php


$(document).ready(function() { //jQuery ready event


       prop: 'someOfPropertyValue',

       prop2: 'anotherProperty'




  1. use AJAX-requests

Thanks again for sharing. I will surely benefit by these good ideas.

We used almost same idea few months ago. But this one is even better!

Also a good way of handling the URL for ajax requests in the javascript controller files is to add a function to our $.app object that replicates the functionality of the Yii function:

<?php echo CController::createUrl('controller/action'); ?>

do it as follows:

$.app = {

    page: undefined,

    init: function () {


        if ($.app.page !== undefined) {

            if (!$.app.page.delayed) // Flag, in case you don't need to load file on start





	createControllerUrl: function( action ) {

		return this.baseUrl + '/index.php?r=' + action;



and then in the header of your main.php file:

	<script type="text/javascript" src="<?php echo Yii::app()->request->baseUrl; ?>/javascripts/app.js"></script>

	<script type="text/javascript">

		// JavaScript Bootstrap

		$(document).ready(function () { 


			$.app.baseUrl = '<?php echo Yii::app()->request->baseUrl; ?>';




so now when you make an ajax request within an action javascript file you can do the following:

...code above

// AJAX request function

myRequestFunction: function() {

	// send request


		url: $.app.createControllerUrl('controller/action'),

		data: { my_data: 'some data', more_data: 'more_data' },

		type: 'POST',

		success: function( response ) {





... code below