I have ajax loading posts on my site when scrolling. The problem lies in the appearance of duplicate posts. I cannot understand why this is happening. Only some posts have duplicates. Here is my code in function.php:
function loadmore_get_posts(){
$paged = !empty($_POST['paged']) ? $_POST['paged'] : 1;
$paged++;
$args = array(
'paged' => $paged,
'posts_per_page' => $_POST['posts_per_page'],
'post_type' => 'post',
'post_status' => 'publish',
'cat' => $_POST['cats']
);
query_posts($args);
while( have_posts() ) : the_post();
get_template_part( 'this is template' );
endwhile;
die;
}
add_action('wp_ajax_loadmore', 'loadmore_get_posts');
add_action('wp_ajax_nopriv_loadmore', 'loadmore_get_posts');
And this is ajax in vanilla javascript:
let ajaxurl = '<?php echo admin_url('admin-ajax.php') ?>';
let section_posts = 1;
let postData = new FormData();
postData.append('action', 'loadmore');
postData.append('paged', section_posts);
postData.append('posts_per_page', 9);
postData.append('cats', <?php print json_encode(get_selected_cats())?>);
const xhr = new XMLHttpRequest();
xhr.open('POST', ajaxurl);
xhr.addEventListener('readystatechange', function (data) {
if (this.readyState === 4 && this.status === 200) {
section_posts++;
document.querySelector('.articlefeed_template').innerHTML += data.target.responseText;
} else {}
xhr.send(postData);
}
Please, tell me what I am wrong about? Thanks!