Search code examples
phpjqueryajaxjsonhref

Get href value after loading the link with AJAX in jQuery


I am trying to update a single record in my database with AJAX. Everything is working fine, but when the result is returned, it looks fine, but if a.update is clicked again (for the returned element) I get the href opened (so the second time the attr() doesn't work for some reason). I am very new to jQuery and ajax :)

    // Update Single Item   
$('li a.update').click(function () {
updateURL = $(this).attr("href");
$(this).attr("href", "#");
theContainer = $(this).parents('li');
    $.ajax({
    type: "GET",
    dataType: 'json',
    url: updateURL,
        async: false,
    success: function(data){
        theContainer.replaceWith(data.html).fadeIn(300);
    }

    });
    return false;
    });

p.s. The List element is generated with PHP. When I request a single <li> element, I generate it with the exact same template (by default everything is printed with a foreach loop, afterwards AJAX requests get back a JSON with <li>...</li>)


Solution

  • You can use the live method to attach the event listener to all matching elements regardless of whether they are already in the DOM or not:

    $('li a.update').live("click", function() {
        //Your code
    });
    

    The way you are attaching the event listener will only attach it to elements currently in the DOM, and as you are adding new ones via AJAX, they don't receive the event listener.