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-

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

    'prompt'=>'Select Region',
    'ajax' => array(
    '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...}',
echo CHtml::dropDownList('city_name','', array(), array('prompt'=>'Select City'));

Code in Controller-

public function actionLoadcities()
   array(':region_id'=>(int) $_POST['region_id']));
   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