Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Click not working after ajax content has loaded

Tags:

jquery

ajax

How can I make live('click',function()" work after an ajax call and returning content with html(data)? After 4 hrs of searching I think I'd better ask because I am getting nowhere.

This part is working:

$.ajax({
    type: "POST",
    url: "loadAlbum.php",
    data: dataString,
    success: function(data){
        $(".loader").html(data, {}, function(){ 
        //content is loaded now
        //need to get the function below working in this part of the content
        }); 
    },
    error : function(data) { } 
    });
});

And I need this one to work in the ajax above:

$('.divName as inside loader').live('click',function(){  

alert('gotClicked');

    var vidItem = $(this).attr('data');
    vidItem = vidItem.split('-'); var bookID = vidItem[0]; var state = vidItem[1];
    var dataString = 'bookID='+ bookID + '&state=' + state;

alert(dataString); 

});
like image 609
KJS Avatar asked Nov 27 '12 13:11

KJS


People also ask

How do you bind events on Ajax loaded content?

The jQuery events (click, change, blur, hover, submit, etc) need to be bind properly in the dynamic content loaded by the Ajax request. You need to use the event delegation for Ajax generated content using jQuery. Use jQuery delegation to attach an event in the dynamically created content by Ajax.

How would you fire a callback when any AJAX request on a page has completed?

The "complete" function executes only after the "success" of ajax. So try to call the printWithAjax() on "complete". This should work for you.

How can I call document ready function after Ajax call?

It would turn into: function OnloadFunction () { alert("test"); } $(document). ready(OnloadFunction); Then you can call OnloadFunction whenever you want to.


1 Answers

.live() is deprecated. Use .on() instead.

$("body").on("click", "divClass", function(event){
    alert('gotClicked');
});

Also, just to make sure you're calling the div correctly, it shouldn't be the div name it should be the div class when calling it in that fashion.

Also, using live() and on() needs to be applied at a parent level that exists at the document load. If this divName you're using didn't exist when the page loaded itself it can't be bound to. However, if you bind to the body element, then it'll always look for the div when the click occurs.

like image 169
Joel Etherton Avatar answered Sep 28 '22 11:09

Joel Etherton