[Solved] Ajax Button Not Working After An Ajax Update Of A Clistview

I have a CListView that contains severals elements. Each of those elements has an ajax link.

At first the ajax links are working well, but when I switch pages in my CListView then the ajax links aren’t working anymore!

Here’s my controller:


$dataProvider = News::model()->listeNews();

$this->renderPartial(

    '_list',

    array('dataProvider' => $dataProvider,),

    false,

    true

);

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

The CListView:


<?php $this->widget('zii.widgets.CListView', array(

'dataProvider'=>$dataProvider,

'itemView'=>'_view',

    'enablePagination'=>true,

    //don't change the id, used to update the number of news to displau

    'id'=>'list',

    'cssFile' => Yii::app()->theme->baseUrl . '/css/widgets/listview/styles.css',

    'template'=>"{pager}\n{items}\n{pager}",

    'pager' => array(

        'class' => 'PagerSA',

        'cssFile'=>Yii::app()->theme->baseUrl . '/css/widgets/pager.css',

        ),

)); ?>

And the ajax link in the item view:


<?php echo CHtml::ajaxLink(

    '<div class="nb_like" id="nb_like_'.$data->id.'">' . $data->like . '</div>',

    array('news/like','id'=>$data->id, 'type'=>'like'),

    array('update'=>'#nb_like_'.$data->id),

    array('class'=>'btn_like', 'id'=> 'like_' . $data->id)

);?>

When I watch the ajax response the javascript is present, but it doesn’t seem to be called after.


jQuery('#list').yiiListView({'ajaxUpdate':['list'],'ajaxVar':'ajax','pagerClass':'pager','loadingClass':'list-view-loading','sorterClass':'sorter','enableHistory':false});

$('body').on('click','#dislike_2810',function(){jQuery.ajax({'url':'/index-local.php/news/like?id=2810&type=moins','cache':false,'success':function(html){jQuery("#nb_dislike_2810").html(html)}});return false;});

And if I’m going again on the first page (that was loaded not using ajax) then the ajax links are still working fine!

Thanks to stackoverflow I managed to make it work:

I replaced the ajaxLink by a normal Link:


<?php echo CHtml::link(

    "<div class=\"like-container\">{$data->like}</div>",

    array('news/like', 'id'=>$data->id, 'type'=>'like'),

    array('class'=>'btn_like')

)) ?>

And with my CLMistView I added the following script:


<?php Yii::app()->clientScript->registerScript('initLikeButtons',<<<JS

    $('body').on('click','.btn_like', function(e) {

        e.preventDefault();

        var that = $(this);

        $.post($(this).attr('href'), function(data) {

            that.children('.like-container').text(data);

        });

    });

JS

, CClientScript::POS_READY); ?>