Gridview Update Through Ajax Works Only The First Time

Hello everyone.

I call controller/create though CHtml::ajaxSubmitButton which updates the grid. Altough the model is created and saved through the ajax call every time as expected, the grid gets updated only the first time and then remains silent. If I manually refresh the page, then the grid shows up all the latest updates. What am I doing wrong…?

EDIT:

The problem comes down to this (in the view):




echo CHtml::ajaxSubmitButton('Καταχώρηση', $this>createUrl('expenses/create',array('id'=>$model->appartmentBlock_id)),

             array(

               'type'=>'post',

               'success'=>'function(data){

                  alert("Starting...");   /*this gets executed every time*/

                  $("#expenses-grid").yiiGridView("update"); /*this gets executed only the first time! */

                  alert("Done!");}', // after the first time, this is unreached.

               ),

             array('id'=>'myAjaxSubmitButton'.uniqid(),

                   'style'=>'width:100px',

                   'live'=>false)

              );



This view (the form) is the outcome of another ajax call into which the controller responds with renderPartial(…, …, false, true). Does the grid update happen only once because the javascripts get mixed up after several ajax calls? But, I use live=>false and ‘id’=>‘myAjaxSubmitButton’.uniqid() on the ajax submit button in the view…

This is my controller:


public function actionCreate($id)

	{

		$model=new Expenses;


		// Uncomment the following line if AJAX validation is needed

		//$this->performAjaxValidation($model);

                

                if(!isset($model->appartmentBlock_id))

                    $model->appartmentBlock_id = $id;

                

                $firstTime = true;




		if(isset($_POST['Expenses']))

		{

			$model->attributes=$_POST['Expenses'];

                        $model->appartmentBlock_id = $id;

                        if($model->save()){

                            

                        }

                        else{

                            $firstTime = false;

                        }

                }


		

	}







public function actionGetRecordDetails($id) {

            //$model = Expenses::model()->findByAttributes(array('id'=>$id)); //findByPK ?

            $model = $this->loadModel($id);

            if($model == Null)

                echo $this->renderPartial('_view', array('model'=>Null), false, false);

            else

                echo $this->renderPartial('_view', array('model'=>$model), false, true);

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

        }

        

        

        public function actionGetNewEmptyRecord($appartmentBlock_id){

            $model = new Expenses();

            $model->unsetAttributes();       

            $model->appartmentBlock_id = $appartmentBlock_id;

            echo $this->renderPartial('_view', array('model'=>$model), false, true);

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

        }



This is my view:




<div>

<table>

<tr>

    <td style="vertical-align: top">

    <div style='height:380px; width:130px;'>

<?php


$expensesViewDetailsLink = CJavaScript::encode($this->createUrl('expenses/getRecordDetails', array('id'=>'')));

$expensesGetNewEmptyRecordLink = CJavaScript::encode($this->createUrl('expenses/getNewEmptyRecord', array('appartmentBlock_id'=>$model->appartmentBlock_id)));

//$emptyExpensesDetails = CJavaScript::encode($this->renderPartial('_view', array('model'=>$model), true));

$expensesUpdateLink = CJavaScript::encode($this->createUrl('expenses/update', array('id'=>'')));

$expensesDeleteLink = CJavaScript::encode($this->createUrl('expenses/delete', array('id'=>'')));




$this->widget('zii.widgets.grid.CGridView', array(

        'id'=>'expenses-grid',

	'dataProvider'=>$model->search(),

        'filter'=>$model,

        //'enablePagination' => false,

        'pager'=>array(

            'class'=>'CLinkPager',

            'header'         => '',

            'firstPageLabel' => '&lt;&lt;',

            'prevPageLabel'  => '&lt;&lt;',// '<img src="'.Html::imageUrl('pagination/left.png').'">',

            'nextPageLabel'  => '&gt;&gt;', //'<img src="'.Html::imageUrl('pagination/right.png').'">',

            'lastPageLabel'  => '&gt;&gt;',

            'cssFile'        => Html::cssUrl('pager.css'),

        ),

        //'afterAjaxUpdate' => 'js:function(id, data) {alert("after");}',

        'summaryText'=>'{start}-{end} / Σύνολο: {count}',

        //'template'=>'{items}{pager}',

        'columns'=>array(

            array(

                'id' => 'selectedIds',

                'class' => 'CCheckBoxColumn'

            ),

            /*array(

                'name'=>'idPlusDate',

                'htmlOptions'=>array('style'=>'width:10px;'),

            ),*/

            array(

                 'name'=>'monthAndYear',

                 'htmlOptions'=>array('style'=>'width:10px;'),

            ),

            /*array(

                'name'=>'informing',

                'htmlOptions'=>array('style'=>'width:45px;'),

            ),*/

            /*

            array(

		'class'=>'CButtonColumn',

                'template'=>'{update}{delete}',

                'deleteConfirmation'=>"js:'Θέλετε σίγουρα να διαγράψετε τα έξοδα '

                    +$(this).parent().parent().text()",

            ),

             */

        ),

        'selectionChanged'=>'function(id){

                if($.fn.yiiGridView.getSelection(id) > 0){

                   $("#expensesUpdateButton").prop("disabled", false);

                   $("#expensesUpdateButton").parent().attr({

                        href: '. $expensesUpdateLink .'+$.fn.yiiGridView.getSelection(id)

                   });

                   $.ajax({

                        url: '.$expensesViewDetailsLink.'+$.fn.yiiGridView.getSelection(id),

                        cache: false,

                        success: function(html){$("#expensesDetails").html(html);}

                   });

                   $("#expensesDeleteButton").prop("disabled", false);

                   $("body").undelegate("#expensesDeleteLink", "click").delegate("#expensesDeleteLink","click",function() {

                        if(!confirm("Θέλετε σίγουρα να διαγράψετε τα έξοδα;")) return false;

                        $("#expenses-grid").yiiGridView("update", {

                            type: "POST",

                            url: '.$expensesDeleteLink.'+$.fn.yiiGridView.getSelection(id),

                            cache: false,

                            success: function(data){

                                $("#expenses-grid").yiiGridView("update");

                                $.ajax({

                                    url: '.$expensesGetNewEmptyRecordLink.',

                                    cache: false,

                                    success: function(html){$("#expensesDetails").html(html);alert("Επιτυχής διαγραφή εξόδων.");}

                                });

                            },

                            error: function(data) {

                                alert("Δεν ήταν δυνατή η διαγραφή των εξόδων."+data);

                            }

                        });

                        return false;

                    });

                }else{

                    $.ajax({

                        url: '.$expensesGetNewEmptyRecordLink.',

                        cache: false,

                        success: function(html){$("#expensesDetails").html(html);}

                   });

                    $("#expensesUpdateButton").prop("disabled", true);

                    $("#expensesUpdateButton").parent().removeAttr(\'href\');

                    $("#expensesDeleteButton").prop("disabled", true);

                }

             }',

    ));


 ?>

    </div>

    <div class="expensesButtonDiv">

         <?php echo CHtml::link(CHtml::button('Νέα Σελίδα', array('style'=>'width:10em', 'class'=>'linkButton')),array('expenses/create', 'id'=>$model->appartmentBlock_id));?>

    

         <?php echo CHtml::link(CHtml::button('Διόρθωση', array('disabled'=>'disabled', 'id'=>'expensesUpdateButton', 'style'=>'width:10em')),array('expenses/update', 'id'=>''));?>

    

         <?php echo CHtml::link(CHtml::button('Διαγραφή', array('disabled'=>'disabled', 'id'=>'expensesDeleteButton', 'style'=>'width:10em')),'#', array('id'=>'expensesDeleteLink'));?>

    </div>

    </td>

    <td>

        <div id="expensesDetails">

            <?php echo $this->renderPartial('_view', array('model'=>$model), false, false); ?>

        </div>

    </td>

</tr>

</table>

</div>



and this is inside _view.php:




<div class="formApp">


<?php $form=$this->beginWidget('CActiveForm', array(

	'id'=>'expenses-form2',

	//'enableAjaxValidation'=>false,

)); ?>


<table class="expDetails">


<?php echo $form->label($model,'monthAndYear'); ?>

                    <?php

                    

                    $describeDateLink = CJavaScript::encode($this->createUrl('expenses/describeDate', array('monthAndYear'=>'')));

                    

                    if($model->isNewRecord){

                      $this->widget('ext.EJuiMonthPicker.EJuiMonthPicker', array(

                        'model' => $model,

                        'attribute'=> 'monthAndYear',

                        'options'=>array(

                            'dateFormat'=>'yy-mm',

                        ),

                        'htmlOptions'=>array(

                            //'onChange'=>'js:$("#month").prop("value", "");',

                            'onChange'=>'js:$.ajax({

                                    url: '. $describeDateLink .'+value,

                                    cache: false,

                                    success: function(html){$(\'#month\').prop(\'value\', html)}

                                });',

                            'size'=>'10px',

                        ),

                      ));

                    }else{

                        echo $form->textField($model,'monthAndYear', array('disabled'=>'disabled','size'=>'10em'));

                    }

                   ?>

                    <?php echo $form->error($model,'monthAndYear'); ?>





<?php

                            if($model->isNewRecord) 

                                echo CHtml::ajaxSubmitButton('Καταχώρηση', $this->createUrl('expenses/create',array('id'=>$model->appartmentBlock_id)),

                                        array(

                                            'type'=>'post',

                                            'success'=>'function(data){alert("Starting..."); $("#expenses-grid").yiiGridView("update"); alert("Done!");}',

                                        ),

                                        array('id'=>'myAjaxSubmitButton'.uniqid(), 'style'=>'width:100px', 'live'=>false)

                                     );

                            else

                                echo CHtml::ajaxSubmitButton('Διόρθωση', $this->createUrl('expenses/update',array('id'=>$model->id)),

                                        array(

                                            'type'=>'post',

                                            'success'=>'function(data){$("#expenses-grid").yiiGridView("update");}',

                                        ),

                                        array('id'=>'myAjaxSubmitButton'.uniqid(), 'style'=>'width:100px','live'=>false,)

                                     );

                    ?>




<div class="row buttons" style="text-align:right;margin:0 50px">

                <?php echo CHtml::link(Chtml::button('Ακύρωση'), array('expenses/index', 'appartmentBlock_id'=>$model->appartmentBlock_id)) ?>	

	</div> 


<?php $this->endWidget(); ?>






Well, the problem was of course the famous loading-several-client-scripts-after-several-ajax-requests and was solved using zaccaria’s ZControler! ( http://www.yiiframework.com/forum/index.php/topic/10427-ajax-clientscript/ )

The only change in /protected/components/Controller.php is:




class Controller extends ZController



This is the new controller methods that do the job:




public function actionGetRecordDetails($id) {

            $model = $this->loadModel($id);

            if($model == Null)

                $this->renderPartialWithHisOwnClientScript('_view', array('model'=>NULL), false);

                //$this->renderPartial('_view', array('model'=>Null), false, false);

            else

                $this->renderPartialWithHisOwnClientScript('_view', array('model'=>$model), false);

                //$this->renderPartial('_view', array('model'=>$model), false, true);

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

        }

        

        

        public function actionGetNewEmptyRecord($appartmentBlock_id){

            $model = new Expenses();

            $model->unsetAttributes();       

            $model->appartmentBlock_id = $appartmentBlock_id;

            ///$this->renderPartial('_view', array('model'=>$model), false, true);

            $this->renderPartialWithHisOwnClientScript('_view', array('model'=>$model), false);

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

        }