Update specific cgridview html row after AJAX request

After of model update (successfull or not) throught CGridView (check the below link) you probably need to updates the specific row html in cgridview (not entire cgridview)

http://www.yiiframework.com/wiki/658/update-cgridview-row-separately-using-ajax-request/

Reasons to do that: 1) You want to reserve the pagination 2) You have comblex html in row that needs updated directly from php 3) improve time request (retrieve the specific html code and not entire cgridview) 4) other reasons, depended of your needs

So, how to do that?

The previous wiki represents how to update a specific row into CGridView Makes the below modifications of the original code

1) In your controller modify the actionSaveModel like that

public function actionSaveModel($id){

        if ($_POST['TheModel']) {
            $model = new TheModel();
            $model->attributes = $_POST['TheModel'];
            
            $saved = $model->save();
            
            if ($saved) {
                    $dataProvider = new CArrayDataProvider(array($model));
                    $this->renderPartial('_gridTable', array(
                        'provider' => $dataProvider,
                    ));
                    Yii::app()->end();
                }
                else
                    echo 'error';

                Yii::app()->end();
            
        }
    }

2) Makes the view file _gridTable.php, migrates the cgridview widget code from the original view file to the _gridTable.php.

Add in the line of the removed code the code


$this->renderPartial('_gridTable', array(
                        'provider' => $dataProvider,
    ));
In this way you use reusable code.

3) Modify the javascript code of the original view file to update only the specific row

$('#grid-view-id a.save-ajax-button').live('click', function(e)
    {
        var row = $(this).parent().parent();
 
        var data = $('input', row).serializeObject();
 
        $.ajax({
            type: 'POST',
            data: data,
            url: jQuery(this).attr('href'),
            success: function(data, textStatus, jqXHR) {
            
                if (data == 'error') {
                    alert("Data has error(s)");
                } else {
                    //this code updates only the specific row
                    var dataT = $('tbody tr',$(data));
                    row.html(dataT.html());
                    /////////////////////////////////////////
                    console.log(data);
                    console.log(textStatus);
                    console.log(jqXHR);
                }
            },
            error: function(textStatus, errorThrown) {
                console.log(textStatus);
                console.log(errorThrown);
            }
        });
        return false;
    });

Thats it!