Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Friday, March 2, 2012

Make ajax request in yii framework

To make ajax request in yii framework is simple to use. For the usual  ajax request from jquery we can use this pattern like this..

$.ajax({
    url:"http://localhost/request.php",//this is the request page of ajax
    data:{params1:param1,param2:param2},//data for throwing the expected url
    type:"POST",//you can also use GET method
    dataType:"html",// you can also specify for the result for json or xml
    success:function(response){
         $('#result_selector').html(response);
    },
    error:function(){
         alert('Failed request data from ajax page");
    }

But in yii the ajax function has been integrated to the yii native function. There are many choices for you to make ajax call through button, link or other components.. From the documentation we can take a look of this part.

ajax()Generates the JavaScript that initiates an AJAX request.CHtml
ajaxButton()Generates a push button that can initiate AJAX requests.CHtml
ajaxSubmitButton()Generates a push button that can submit the current form in POST method.CHtml
That's the list of function supported by yii function. you can use that to populate the ajax request just use that function.

Oke let's take a look below code for the example

<?php
       echo CHtml::ajaxButton(
            'Submit request',
            array('test/function'),
            array('data'=>array('test'=>$model->id)),
            array('update'=>'#update_selector')//this is the update selector of yours $('#update_selector').load(url);
        );
?>
And then don't forget if you want to make an ajax call you should have to use renderPatial so the whole contents is not included.
public function actionFunction() {
 if(Yii::app()->request->isAjaxRequest){
  $this->renderPartial("_form",array('model'=>$model),false,true);
  Yii::app()->end();

 }
}
That's the easy look of yii function..