Ajax links dont work when they've been generated by another AJAX action


I have an application with a shopping cart.

When a user inserts something into the cart, the cart div gets updated through ajax.

The cart also contains some remove like this

<?php echo CHtml::ajaxLink('remove',array('store/remove_from_cart','id'=>$cart_item->product->id),array('update' => '#cart')); ?>

after the cart was updated once, the remove links don’t work any more.

It appears that the needed javascript is not being included in the output.

Any pointers?

When you render the new content for the #cart (probably in the add_to_cart action of the store controller ) you have to use


renderPartial($view, $data, false, true)


My cart is actually a widget so I had to create new view file

This was my old code

    if(Yii::app()->request->isAjaxRequest) {


    } else {



and I had to replace $this->widget(‘PCart’); with $this->renderPartial(’_cart’, array(), false,true);

I have one question though:

I notice that by doing it this way Yii is including jquery.js again even though it is already present on the page that the cart is rendered into.

Is there any way to tell Yii not to do it in the case of an AJAX request?

It really doesn’t make any sense

sorry for the bump.

Does anyone know a way to prevent Yii from loading jQuery again in an AJAX request but still have the event handlers registered?

This problem (or similar) has been discussed before in this forum so I did some research.

The replaced links need to have the click event rebound. jQuery.live() or the JQuery extension liveQuery can do that. (Some say the latter has to be used for IE, when I tested both seemed to work)

I think it’s a good idea to separate the javascript from the partial view. Here are my suggestions:

  1. Register the JS library(s)



  Yii::app()->getClientScript()->registerScriptFile(Yii::app()->request-baseUrl.'/js/jquery.livequery.js', CClientScript::POS_HEAD);

  1. Register the jQuery script


    Yii::app()->getClientScript()->registerScript('test', "

      $('#cart a')

        //.livequery('click', function(){

        .live('click', function(){





          'data':jQuery(this).attr(\"id\"),  // still have to find out how to pass the clicked id



        return false;



  1. Use ordinary Chtml::link() in the partial view


  echo CHtml::link('remove', '#', array('id'=>'link1'));

  echo CHtml::link('remove', '#', array('id'=>'link2'));

Not sure if this will completely solve your problem but it’s at least worth to consider.

Edit: Removed comment about possible need for unique element id. (I introduced timestamping because I didn’t realize it already was ok under IE.)

Edit: Fixed the Ajax URL.

Edit: Simplified the Ajax URL (still learning :rolleyes: ).


Excellent post. This is a great reason why Yii should have a wiki soon rather than later.