automated routing to ajax actions

Hi there

I’ve created a controller which is used for normal requests and ajax requests. The first line of each action checks with Yii::app()->request->isAjaxRequest if it’s an ajax request. If so it calls an ajax function like this:

public function actionView()








This way I can use the URL for the normal and the ajax request. My problem is that I’m repeating myself over and over. I want to remove the if/elses showed above. So what is the best way to route all ajax requests for index.php?r=controllerID/actionID to controllerID/actionIDAjax automatically? (Without using redirects).

e.g. index.php?r=post/view would call the action “actionViewAjax” within the “post” controller if it’s an ajax requet.

Should I override parseUrl() of the url manager? Can I get it work with routing rules?


IMHO this should be implemented as class-based filter, so you can use in at any number of controllers just overriding its filters() method.

Example implementation of such filter (not tested):

class AjaxActions extends CFilter {

  protected function preFilter($filterChain) {

	if ( Yii::app()->request->getIsAjaxRequest() ) {

  	$method= 'action' . ucfirst($this->action) . 'ajax';//build target method name

  	//if method exists - use it, otherwise - do things as usual

  	if (method_exists($filterChain->controller, $method)) {





	return true;



That’s a good idea. Never thought about using a filter.

Thank you very much! :)