Social Icons

Pages

Tuesday, July 2, 2013

Yii ajax request and json response

This  will help you to understand the details of yii ajax request and response from controller.

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>
?>






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



1 comment:

  1. Sounds interesting. this blog is very nice. and thanks for giving such a wonderful knowledge.

    If you like to learn about Yii 2.0 beta version, please visit this video: www.youtube.com/watch?v=WwT6ar8nQGk

    ReplyDelete