Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    Regular Coder
    Join Date
    Nov 2007
    Posts
    108
    Thanks
    14
    Thanked 0 Times in 0 Posts

    After partial-page reload with AJAX, javascript function won't fire

    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:
    Code:
    <script type="text/javascript">
        
      $(document).ready(
    	function() {
    	
    		$('.remove').click(function(ev) {
    		   alert("Remove clicked...");
    		   currentId = $(this).attr('id');
           		   ev.preventDefault();
    	           $.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):

    Code:
     <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?

  • #2
    Regular Coder
    Join Date
    Nov 2007
    Posts
    108
    Thanks
    14
    Thanked 0 Times in 0 Posts
    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:
    Code:
    $('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.
    Last edited by loamguy1; 12-17-2010 at 10:43 PM.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •