How to avoid rendering entire page on AJAX call for CGridView and CListView

You are viewing revision #5 of this wiki article.
This is the latest version of this article.
You may want to see the changes made in this revision.

« previous (#4)

CGridView and CListView are great widget to populate records and also provides features like ajax update, column sort, search, drop-down filter, ajax content load and many more...

Both works great but has lankness in Ajax content load. When it request for next page content then Ajax comes with entire web page content and off-course executes all scripts before send output.

Not understanding Anh...., Don't worry see it in action by your self. If your are using any CGridView/CListView then click on any next page and see response using FireBug. There will be entire page content instead only grid/list view content.

Do Fix

Lets go to apply some tricks to prevent entire page content output and script execution...

Step 1: Create a partial view file for CGridView or CListView

Create Partial File: ___grid_view_forsubscriber.php

$this->widget('zii.widgets.grid.CGridView', array(
  'id' => $grid_id,
  'dataProvider' => $subscriberActiveDataProvider,
  'columns' => array(
    'first_name',
    'last_name',
    'designation',
    'company',
    'subscribed_on',
  ),
));

Step 2: Main view file

Create View File: subscribers_list.php

/* @var $this SubscriberController */

$this->pageTitle = 'Subscribers';

// Render partial file created in Step 1
$this->renderPartial('__grid_view_for_subscriber', array(
  'subscriberActiveDataProvider' => $subscriberActiveDataProvider,
  'grid_id' => $grid_id,
));

Step 3: Controller Class

Controller Class: SubscriberController.php

class SubscriberController extends Controller {
  //
  
  public function actionList() {
    $criteria = new CDbCriteria();
    // Add your Query condition here
    // $criteria = 'your condition here';

    // Create `activeDataProvider` object for Subscriber model
    // NOTE: Subscriber model is not included in this article
    // Replace model name with your's
    $subscriberActiveDataProvider = new CActiveDataProvider('Subscriber', array(
      'criteria' => $criteria,
    ));

    $grid_id = 'subscriber_grid';

    // Check is for AJAX request by `subscriber_grid`
    // ajax response only grid content instead entire web page
    if(Yii::app()->request->isAjaxRequest && isset($_GET['ajax']) && $_GET['ajax'] === $grid_id)) {
      // Render partial file created in Step 1
      $this->renderPartial('__grid_view_for_subscriber', array(
        'subscriberActiveDataProvider' => $subscriberActiveDataProvider,
        'grid_id' => $grid_id,
      ));
      Yii::app()->end();
    }
    
    // Render main view file created in Step 2
    $this->render('subscribers_list', array(
      'subscriberActiveDataProvider' => $subscriberActiveDataProvider,
      'grid_id' => $grid_id,
    ));

  }

  //
}

: THANKS :