View Full Version : After partial-page reload with AJAX, javascript function won't fire

12-16-2010, 04:16 PM
The good news is that when I use AJAX to reload part of a page within a DIV block, the HTML content successfully reloads. There are <a> links in this block which, before the AJAX reload, successfully trigger a javascript function.

The bad news is that if I click an anchor tag in the reloaded block, the associated javascript function does not fire. No errors either, but nothing happens.

The class name and id name of the <a> element is the same as when before the AJAX reload occurred. Before the AJAX routine runs, clicking the <a> tag successfully triggered the javascript function.

Here's the function that is supposed to fire:

<script type="text/javascript">

function() {

$('.remove').click(function(ev) {
alert("Remove clicked...");
currentId = $(this).attr('id');
$.blockUI({ message: $('#blockMsg'), css: { border:'none',width: '275px'} });

The <a> block looks indentical before and after when I look at the page source. It looks something like this (the id number is dynamic):

<a class="remove" id="111" href="#" ><img src="/images/error_icon.png" alt="Remove" title="Remove" /></a></td>

After the AJAX reload, I do not get any javascript errors in Firebug or Chrome when I click the <a> link. Just nothing happens.

But then if I refresh the browser, clicking the link fires the function again.

Do I need reload the javascript function or something to that effect?

12-17-2010, 09:14 PM
Ok, so I found the answer after coming up empty on Google:

I implemented the jQuery live() function which 'remembers' to use the event handler for current and future inclusions of the class.

The old code above was not attaching the event handler if a new anchor tag was loaded into the DOM via AJAX.

And this is what fixed the problem:

$('a.remove').live('click', function(ev))

Now if I load HTML content via AJAX with an anchor tag class of 'remove', clicking the link will work.