How to use CHtml::ajax()

Hi:

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.

View:




CHtml::ajax(array(

	'id'=>'country_list',

	'type'=>'POST',

	'url'=>CController::createUrl('countries/findallcountries'),

	'update'=>'#ctrylist',

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

	));

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

.

.

.




CountriesController:




public function accessRules()

{

	return array(

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

			'actions'=>array('index','view'),

			'users'=>array('*'),

		),

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

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

			'users'=>array('@'),

.

.

.

public function actionFindAllCountries()

{

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

	{

		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);

		}

	}

	else

	{

		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(

      "test",

      "jQuery.ajax({

            type: 'POST',

            url: '".$url."',

            success: function(html){

               jQuery('#yourID').html(html);

        }

          });

      ",

      CClientScript::POS_READY

  ); ?>



$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.