How to use CHtml::ajax()


I’ve been playing with the CHtml::ajax() function to send a request from the view through the controller to the model to automatically retrieve some data upon page loading, with no results.







//	'data'=>'js:jQuery(this).serialize()',	// only send element name, not whole form


echo CHtml::textArea('ctrylist', '');





public function accessRules()


	return array(

		array('allow',  // allow all users to perform 'index' and 'view' actions




		array('allow', // allow authenticated user to perform 'create' and 'update' actions

			'actions'=>array('create','update', 'findallcountries', 'findcountrybyregionid'),





public function actionFindAllCountries()




		return Countries::model()->findAllCountries($_POST['country_list']);



Countries model:

public function findAllCountries()


	$criteria = new CDbCriteria(array(

		'select'=>'country_code, country_name',

		'order'=>'country_code ASC',


	$reglist=CHtml::listData($this->findAll($criteria), 'country_code', 'country_name');

	if (isset($_POST['country_list']))


		foreach($reglist as $value=>$name)


			echo CHtml::tag('option', array('value'=>$value),CHtml::encode($name),true);





		return $reglist;



It seems that the Ajax call is not executed because even if I insert a print_r(‘Hello’) in the controller function it doesn’t execute. How does this function work?

Thanks for the help,

I did and it worked for me. Hope that help.

You can try to register ajax script via jQuery

For example:

  <?php   Yii::app()->clientScript->registerScript(



            type: 'POST',

            url: '".$url."',

            success: function(html){






  ); ?>

$url is url that you make via urlManager or CController::createUrl

I wasn’t aware that I had to register the script so I will give your suggestion a try. Thanks for your help.