An Easy Solution for Dependent dropDownList Using AJAX

Sometimes new Yii guys face problem to manage dependent dropDownList using AJAX. I am going to discuss an easy solution about this issue.

Example code:

Code in View-

<?php									
  echo CHtml::dropDownList('region_id','', 
  array(2=>'New England',1=>'Middle Atlantic',3=>'East North Central'),

  array(
    'prompt'=>'Select Region',
    'ajax' => array(
    'type'=>'POST', 
    'url'=>Yii::app()->createUrl('YourController/loadcities'), //or $this->createUrl('loadcities') if '$this' extends CController
    'update'=>'#city_name', //or 'success' => 'function(data){...handle the data in the way you want...}',
  'data'=>array('region_id'=>'js:this.value'),
  ))); 
									 
								
 
echo CHtml::dropDownList('city_name','', array(), array('prompt'=>'Select City'));
?>

Code in Controller-

public function actionLoadcities()
{
   $data=RegionCity::model()->findAll('region_id=:region_id', 
   array(':region_id'=>(int) $_POST['region_id']));
	 
   $data=CHtml::listData($data,'id','city_name');
		
   echo "<option value=''>Select City</option>";
   foreach($data as $value=>$city_name)
   echo CHtml::tag('option', array('value'=>$value),CHtml::encode($city_name),true);
}

I think this will help to understand actually how AJAX works in Yii for dependent dropDownList also AJAX working behavior in Yii framework.

--Enjoy, Explore... Yii