Yii ajax request and json response array

This tutorial will help you to understand the details of yii ajax request and response from controller. I will change the product list based on category change via ajax. When i change the “category” dropdown, Ajax will send the request to “site/productlist” controller. Now controller will get and process the data then finally It will return the json encoded array.Using this response we can update product drop down list.

In view.php

<?php

Yii::app()->clientScript->registerScript('productform','

$("#category").live("change",function(){    
 $.ajax({
   url:'".Yii::app()->createAbsoluteUrl("site/productlist")."',
   type:"POST",            
   data:"catid="+$("#Cat_id option:selected").val(),
   dataType:"json",
   "success":function(data){                
         if(data==null){
              $("#product_type").empty();    
         }else{
              var obj = eval(data);
              $("#product_type").empty();
              $.each(obj, function(key, value) {
                 $("#product_type").append("<option value="+key+">"+value+"</option>");
              });
                    
         }
       }
      });
    });
');
?>

<div class="row">
<?php echo $form->labelEx($model,'category'); ?>
<?php echo $form->dropDownList($model,'category',$categorylist); ?>
<?php echo $form->error($model,'category'); ?>
 </div>

<div class="row">
<?php echo $form->labelEx($model,'product_type'); ?>
<?php echo $form->dropDownList($model,'product_type',
                                array(''=>'Select Product')); ?>
<?php echo $form->error($model,'product_type'); ?>
 </div>
?>

In Controller.php

<php
class SiteController extends Controller
{
public function actionProductlist()
 {
  if(Yii::app()->request->isPostRequest)
  {
    if(isset($_POST['catid']) && $_POST['catid']!=''){
       $Productmodel=Product::model()->
                         findAll(array('condition'=>'isactive=1 and 
                         catid='.$_POST['catid'],'order'=>'name'));
       if($Productmodel){
          $data=CHtml::listData($Productmodel,'productid','name');
          print_r(json_encode($data));
       }
    }
  }
  else
   throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
 }
}
?>

Leave a Reply

Your email address will not be published. Required fields are marked *