masterhunter masterhunter - 14 days ago 5
Ajax Question

Ajax stop working if loaded by infinite scrolling in laravel 5.2

I am learning ajax and jquery now, i currently develop a page which user can like/dislike post, and the all the post will display by loaded with infinite scroll, by default each time will load 5 post, but the problem is if the post is loaded by infinite scroll then the ajax button will stop working. After i doing some research and i know that is because the function is not loaded. But i cannot found the solution for that, can someone help me here?

This is my ajax button function

$('.agree').on('click',function(event){
{
event.preventDefault();
postId = event.target.parentNode.parentNode.dataset['postid'];
var isAgree=event.target.previousElementSibling== null;
$.ajax({
method:'POST',
url:urlAgree,
data:{ isAgree: isAgree,postId:postId,_token:token}
})
.done(function() {
event.target.innerText = isAgree ? event.target.innerText == 'Agree' ? 'You agree this post' : 'Agree' : event.target.innerText == 'Disagree' ? 'You disagree this post' : 'Disagree';
if (isAgree) {
event.target.nextElementSibling.innerText = 'Disagree';
} else {
event.target.previousElementSibling.innerText = 'Agree';
}
});

}


});

Here is the infinite scroll function.

$(document).ready(function() {
$(window).scroll(fetchPosts);

function fetchPosts() {

var page = $('.endless-pagination').data('next-page');

if(page !== null && page !== "") {

clearTimeout( $.data( this, "scrollCheck" ) );

$.data( this, "scrollCheck", setTimeout(function() {
var scroll_position_for_posts_load = $(window).height() + $(window).scrollTop() + 100;

if(scroll_position_for_posts_load >= $(document).height()) {
$.get(page, function(data){
$('.posts').append(data.posts);
$('.endless-pagination').data('next-page', data.next_page);
})

}
}, 350))

}
}


});

Is there any possible way to combine both function together?

Answer

delegate your click event

$('.posts').on('click','.agree',function(event){