How to avoid multiple Ajax Request

  1. What's going on exactly?
  2. What's causing the problem?
  3. What can I do to avoid this problem?

CHtml::ajaxLink(), CHtml::ajaxSubmitButton() 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?

Easy solution

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

You can achieve this result doing something like this:

CHtml::ajaxLink('send a message', '/message', 
    array('replace' => '#message-div'), 
    array('id' => 'send-link-'.uniqid())
);
17 0
27 followers
Viewed: 66 914 times
Version: 1.1
Category: How-tos
Written by: nickcv
Last updated by: nickcv
Created on: Apr 21, 2011
Last updated: 13 years ago
Update Article

Revisions

View all history

Related Articles