Jquery Event won't fire after ajax call

This is a rather strange issue with jquery. I am loading a div

<div id="container">

on page load. Each record is tabular data with a 'delete' ajax function associated with it. When the page loads and clicking the 'delete' link, the ajax call fires off just fine. However, once the event is fired, the data is returned from the ajax call, and the div is populated with data (but the page does not refresh or reload) When I click the link again, the ajax script will not fire. Here is my code:

$(document).ready(function() {
    }).click(function() {
        var BatchID = $("input#BatchID").val();
        var Amount = $("input#Amount").val();
        var Name = $("input#CheckName").val();
        var Check_Number = $("input#Check_Number").val();
        var Company = $("select#Company").val();
        var Department = $("select#Department").val();
            type: 'GET',
            url: '/app/usagCheckEntryWS.html',
            data: {
                "BatchID" : BatchID,
                "Amount" : Amount,
                "Name" : Name,
                "Check_Number" : Check_Number,
                "Company" : Company,
                "Department" : Department
            success: function (data) {
                    var ang = '';
                    var obj = $.parseJSON(data);
                    $.each(obj, function() {
                       ang += '<table><tr><td width="45">' + this["RefID"] + '</td><td width="140">' + this["Name"] + '</td><td width="95">' + this["CheckNumber"] + '</td><td align="right" width="70">$' + this["Amount"] + '</td><td width="220" style="padding-left: 15px;">' + this["Description"] + '</td><td><div class="delete" rel="' + this["RefID"] + '"><span>Delete</span></div></td></tr></table>';



When you remove an element and then replace it (via javascript), it loses any event bindings that were added to it on page load.

(This also applies to content added to the page after page load - i.e. ajax loaded content)

There are several possible solutions for this.

1) Encapsulate your "binding" code and call it both on page load and immediately after the element in question gets added back to the page. For example:

    // bind event handlers when the page loads.

function bindButtonClick(){
        ... event handler code ...

function updateContent(){
        url : '/ajax-endpoint.php',
        data : {'onMyWay' : 'toServer'},
        dataType : 'html',
        type : 'post',
        success : function(responseHtml){
            // .myClickableElement is replaced with new (unbound) html element(s)

            // re-bind event handlers to '.myClickableElement'

2) The more elegant way to handle this: use jQuery's .on() method. With it, you are able to bind event handlers to elements other than the event target - i.e. an element that never gets removed from the page.

        ... event handler code ....

Some further explanation:

The .on() method uses event delegation to tell a parent element to retain your event handler code (3rd argument), and fire it when the event target (2nd argument) has a certain type of event (1st argument) performed on it.

If you are using a version of jQuery prior to 1.7 use the now deprecated delegate method which essentially does the same thing.

Also, it is worth noting that because of the way events "bubble up" through the dom tree, the event target (2nd argument of .on() method) must be a descendant of the delegating element (jQuery object's selector). For example, the following would NOT work

<div id="container-1">
        <div id="another-div">
            Some Stuff

<div id="container-2">
    <a id="click-me">Event Target!!!</a>

<script type="text/javascript">
        ... event handler code ....
        // This will never execute, should've used '#container-2', or 'body', or 'document' instead of '#container-1'

The body or document elements are usually safe choices since typically every element on the page is a descendant.


You can enclose the event script in DIV and run a Replaceall command after dynamically loading the content.

<div class="somescript">
-- Event Script that you want to map with dnamically added content

-- Dynamically load your content and run the below command after it.


Once the dynamically loaded content is loaded and replace command has been run, the events will be mapped and code will run fine.


My comment is too long, sorry.

Just a question and a comment, although I see that this is an old post. I have had a lot of trouble using: $(document).on('click', '#xxx", function(e) { }); to attach handlers to content returned using AJAX, vs. using a function () { $('#xxx).on('click', function(e) { }); } and calling that after the AJAX call returns with success. Is there some sort of trick or guideline for using that method ? I get the delegation involved, and I have tried using that but it does not often work. I could try delegating to the enclosing element. Maybe it does not bubble up to the document or the body for some reason ?


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.