Lual Lual - 2 months ago 10
Ajax Question

Load specific parts of (WordPress) next posts page via AJAX

What I'm trying to do exactly



I'm creating a custom WordPress site, it displays a "load more posts" button in the pages blog (main), category and search results. When the user clicks this button, the script retrieves the posts in the next page and appends them inside a container. Here's the code:

<script>
document.addEventListener("DOMContentLoaded", function() {

// display or not the btn when page is loaded

var morePosts = $("#dom-target").text();

if (morePosts != "true") {
$('.load-more').css('display','none');
}


// button functionality

var pageIndex = 1;
var numOfPages = Number($('#numOfPages').text()); // parsed from php
var nextLink = $('#nextLink').text(); // parsed from php

$('.load-more').click(function(){

if (pageIndex < numOfPages) {

var nextPosts;
$.get(nextLink+' .post-card', function(data){

// get articles in next page
nextPosts = data;

// append articles
$('#content').append(nextPosts);

// change value of index and redefine nextLink
pageIndex++;
nextLink = nextLink.replace(pageIndex+'/',pageIndex+1+'/');

// check if button display is still needed
if (pageIndex == numOfPages) {
$('.load-more').css('transition','all 0s');
$('.load-more').fadeOut();
}
});
}
});
});
</script>





The problem: It loads the entire page



I wonder if
$.get()
has a equivalent for
.load('main url .specific-class')
, because when I try to apply the analogous syntax

$.get(nextLink+' .post-card')


the console threw me

GET http://localhost/blog/page/2/%20.post-card 404 (Not Found)


Or if there is a way to parse the data (a string) as an HTML document (so I can apply jQuery to the variable that stores the data and get just the post cards instead of the entire page).



Thanks in advance! :)

Answer

You have to parse the response yourself which you can do simply by wrapping in $() and using any jQuery method on

$.get(nextLink, function(data){
     var nextPosts = $(data).find('.post-card');
      $('#content').append(nextPosts);
     //.......

});