user2951112
user2951112

Reputation: 105

when ajax load content like and delete button not work

hi am getting every time same problem when ajax load dynamicaly content eg: comments or any post then all work fine. but comment like button not work until i refresh the page . below my like script help me how i solve this issue

$(".comment_like").click(function()
{
var cID = $(this).attr("ccid");
var cREL = $(this).attr("rel");
var cbox = $(this).attr("box_id");
var cowner = $(this).attr("ownercli");
var cURL='comment_like.php';
var dataString = 'msg_id=' + cID +'&rel='+ cREL+ '&owner='+ cowner+ '&cbox='+ cbox;
if(cREL=='Like')
{
$('#c'+cID).html('Unlike:').attr('rel', 'Unlike').attr('title', 'Unlike');
}
else
{
$('#c'+cID).attr('rel', 'Like').attr('title', 'Like').html('Like:');
}
        xhr = $.ajax({
            type: "POST",
            url: cURL,
            data: dataString,
            cache: false
        }).done(function(htmlc){
      $('.cml'+cID).html(htmlc);
        });
});

Upvotes: 2

Views: 379

Answers (2)

David Aguirre
David Aguirre

Reputation: 1410

Click events are only bound to the elements already in the DOM. If you are loading the container from the ajax call the click event will not be bound to it. It's not really correct IMO, however you can quickly fixx this by adding the click events into the .done function. Once the ajax call is done the click event is then bound to the elements dynamically added to the DOM.

Upvotes: 0

Daved
Daved

Reputation: 2082

Is it safe to assume the $(".comment_like") button is within the HTML coming back from the ajax call? If so, this is where the jQuery "on" binding is helpful. Instead of binding on the button itself, which doesn't exist until the content is loaded, you bind the event listener to a container that the element might end up within. In a nutshell, when a click occurs on that container, jQuery checks the element clicked to see if it matches and triggers your handler.

Read: http://api.jquery.com/on/

It's done this way so content can be dynamically loaded, as well as it prevents hundreds of event handlers being bound.

Based on that, instead of

$(".comment_like").click(function() {...});

Try

$('#container').on('click','.comment_like',function() {...});

Where #container is the wrapper containing the HTML you are loading.

Upvotes: 2

Related Questions