I'm trying to add Ajax to my theme so I can load my posts dynamically. The following code works but for some reason when I wrap the button that fires the loading with another div it doesn't do anything.
Full Code: https://pastebin.com/8DhmC32R
JS
jQuery(function($){
$('.loadmore').click(function(){
var button = $(this),
data = {
'action': 'loadmore',
'query': loadmore_params.posts,
'page' : loadmore_params.current_page
};
$.ajax({
url : '/wp-admin/admin-ajax.php',
data : data,
type : 'POST',
beforeSend : function ( xhr ) {
button.text('Loading...');
$('.loadmore').addClass('newcomment');
},
success : function( data ){
if( data ) {
button.text( 'More posts' ).prev().before(data);
$('.loadmore').removeClass('newcomment');
loadmore_params.current_page++;
if ( loadmore_params.current_page == loadmore_params.max_page )
button.remove();
} else {
button.remove();
}
}
});
});
});
The problem:
<div><button class="loadmore">Load More</button></div>
It works without the div class
Finally this is the first time I'm using admin-ajax.php in the frontend is it safe to use for my approach?
Thank you
<div>? That's an odd behaviour. When you check your dev tools is it still sending the data?<button>outside in anything not only in a<div>,<button class="loadmore">Load More</button>. It shows me the message in the console when the data POST successfully. I'm trying to figure out what's wrong hours now.id="loadmore"to the button and then modifying your JS to match? Maybe there's an ambiguity in the targeting if you wrap it. I can't imagine there would be, but it's a small change.<div class="show-more col-12"><button class="loadmore">Load More</button></div>Thank you