Site icon Hip-Hop Website Design and Development

How to set post limit at load more ajax wordpress

The site has load more posts functionality using ajax on vanilla javascript.

Ajax:

postData.append("action", "loadmore");
postData.append("paged", section_posts);
postData.append("posts_per_page", 9);

const xhr = new XMLHttpRequest();
xhr.open("POST", ajaxurl);
xhr.addEventListener("readystatechange", function (data) {
    if (this.readyState === 4 && this.status === 200) {
        section_posts++;
        document.querySelector(".box").innerHTML += data.target.responseText;
    } else {}
});
xhr.send(postData);

This is code action ajax at 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'
  );

    $data = new WP_Query( $args );
 
    while( $data->have_posts() ) : $data->the_post();
      get_template_part( 'templates/...' ); 
    endwhile;
  die;
}
add_action('wp_ajax_loadmore', 'loadmore_get_posts');
add_action('wp_ajax_nopriv_loadmore', 'loadmore_get_posts');

This functionality works well! But I need to set a limit on the number of total posts. Those. the total number of posts is 100, but I need 50 posts to be loaded.

I have read many articles on this topic and tried many methods, but nothing helped. Basically stackoverflow advises to use posts_per_page, but I already use posts_per_page.

Please, tell me how to solve my question. I need to make a limit on the total number of posts.

Thanks!