How To Load Drop-Down List Via Ajax

Hi All

I had 2 table countries and Cities and i need to load cities via country by Ajax .

tbl_countries :









	<div class="row">

		<?php echo $form->labelEx($model,'country'); ?>

	<?php echo chtml::activeDropDownList($model,'country',$model->getcountry(),array('prompt'=>'Select Your Countries ')




	); ?>





		<?php echo $form->error($model,'country'); ?>





	/// Get country detalis intow dropswon list 

	public function getcountry(){


   	return array (











I need small code via ajax with controller example .

Thanks in advance

Thanks my bro redguy but I when i tested example on my localhost returned this message ?!

[b]Undefined index: country_id 	[/b]

view :


/* @var $this CurrentController */






<div class="form">

<?php $form=$this->beginWidget('CActiveForm', array(



)); ?>



 echo chtml::activeDropDownList($model,'country',$model->getcountry(),array('prompt'=>'اختر بلدك')







echo CHtml::activeDropDownList('country','', array(1=>'USA',2=>'France',3=>'Japan'),


'ajax' => array(

'type'=>'POST', //request type

'url'=>CController::createUrl('currentController/dynamiccities'), //url to call.

//Style: CController::createUrl('currentController/methodToCall')

'update'=>'#city_id', //selector to update

//'data'=>'js:javascript statement' 

//leave out the data key to pass all form values through



//empty since it will be filled by the other dropdown

echo CHtml::dropDownList('city_id','', array());


<?php $this->endWidget(); ?>

</div><!-- form -->

Controller :

class CurrentController extends Controller


public function accessRules()


		return array(

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






public $country_id;

	public function actionIndex()





public function actionDynamiccities()



              	array(':parent_id'=>(int)  $_POST['country_id']));



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


    	echo CHtml::tag('option',





also if change $data=Cities::model()->findAll(‘country_id=:parent_id’, in controller to


return city list as text

What’s wrong here ?!!

Thanks in advance


echo CHtml::activeDropDownList('country','', array(1=>'USA',2=>'France',3=>'Japan')

is wrong. "active*" methods are only for activerecord scenarios (you must provide model instance and attribute name).


if using active* method form element name will have name like "ModelName[attribute_name]". You could also debug and check what is really posted to actionDynamiccities.

Anyway - always better is to use Yii::app()->request->getPost( “xxxx”, “default value” ); which won’t trigger “Undefined index”.

OK , Thank you Bro . I will try to fix it .