Difference between #4 and #3 of How to avoid multiple Ajax Request

unchanged
Title
How to avoid multiple Ajax Request
unchanged
Category
How-tos
unchanged
Tags
ajax request, ajax link, ajax request multiply
changed
Content
[CHtml::ajaxLink()](http://www.yiiframework.com/doc/api/1.1/CHtml#ajaxLink-detail),
[CHtml::ajaxSubmitButton()](http://www.yiiframework.com/doc/api/1.1/CHtml#ajaxSubmitButton-detail)
and similar methods are great, but if they are located inside a portion of the
page that is already loaded via ajax something bad will happen, something you
may even not notice if you are not using tools like firebugs: **the sent ajax
requests will multiply themselves**.

##What's going on exactly?  

Let's set up an example:  
you have a page with a list of users. Every time you click on a username a div
will be loaded via ajax, and this div will contain the user details plus another
ajax link that will be used to display a floating div that will contain a form
to send a message to the user.  

The first time you load the user everything will be going just fine, and when
you click on the "send a private message to the user" link just one
request will be triggered.  

If you load then another user (or the same user) when you click on the
"send a message" link two request will be triggered, and then 3, and
then 4 and so on.

##What's causing the problem?  

The ajax request are triggered based on the link ID. Every time the div is
reloaded through ajax a new delegate/event will be loaded pointing at the same
ID of the one before him. So when you actually click on the link both delegates
will do their job, because both match the clicked link.  

##What can I do to avoid this problem?  

The answer is extremely simple: **assign to your ajax link a random ID**.  

You can achieve this result doing something like this:


~~~
[php]
CHtml::ajaxLink('send a message', '/message', 
    array('replace' => '#message-div'), 
    array('id' =>
'send-link-'.rand())'send-link-'.uniqid())
);
~~~