By: Prem Tiwari | Last Updated: | In: Yii framework
In this post i will explain the easy way to get the Ajax request and json response array in Yii framework. The controller will get and process the data then finally It will return the json encoded array.Using this response we can update the database tables.
In view/_form.php page
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
<?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 Your controller page
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<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.'); } } ?> |
Prem Tiwari is the founder of FreeWebMentor.com and also a professional developer who has vast experience in PHP and open source technologies. Apart from this, he is a blogger by hobby and also he has been a regular speaker of WordPress sessions in various IT Companies. View all posts by Prem Tiwari