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.');
    }
}
?>

  • Wow… good! Thanks mbala! 🙂

  • nilo

    how can i show a alert message if data==null
    view.php , line 12

    • mbala

      It is javascript only. So We can use alerty() function
      if(data==null){
      alert(‘hai’);
      }

  • Deora Rahul Singh

    $(function(){

    $(‘#save_value’).click(function(){

    var myCheckboxes = new Array();

    $(‘:checkbox:checked’).each(function(){

    myCheckboxes.push($(this).val());
    });

    });

    how to paas array walue in my controller i am using yii2