AJAX load more posts not using correct category and repeating the same few posts

I solved the issues this way:

In my functions.php file, I added the following code:

if (empty($cat_id)) {
    $cat_id = array(3, 4, 28, 35, 353);
}

In my second AJAX function like so:

function afp_load_more() {
  $cat_id = $_POST['category__in'];
  if (empty($cat_id)) {
    $cat_id = array(3, 4, 28, 35, 353);
  }
...etc

So that when the categoryIDs from my JavaScript returned an empty array (before a user clicks any checkboxes), it would default to the five categories chosen for the checkbox filters.

In my JavaScript, I didn’t have to change much as I discoved the categoryIDs variable was usable by my second AJAX call as-is. The only change I made for that issues was to add category__in: categoryIDs to my second AJAX call under the data array.

For the issue of the repeating posts, I realized I just needed to set up a primative counter to add the value of the posts_per_page to the offset parameter in my query.

Here’s my finished, working JavaScript for the load-on-scroll AJAX call (changes are noted in comments):

// AJAX Load More Posts scripts
var canBeLoaded = true;
var bottomOffset = 1500;
var page = 2;
var postOffset = 9; // Added a variable for the offset
var loading = false;
var scrollHandling = {
  allow: true,
  reallow: function () {
    scrollHandling.allow = true;
  },
  delay: 400
};

$(window).scroll(function () {

  if (!loading && scrollHandling.allow) {
    scrollHandling.allow = false;
    setTimeout(scrollHandling.reallow, scrollHandling.delay);
    if ($(document).scrollTop() > ($(document).height() - bottomOffset) && canBeLoaded == true) {
      loading = true; // This is important but I forgot it last time around
      $.ajax({
        type: 'POST',
        url: afp_vars.afp_ajax_url,
        data: {
          action: "afp_load_more",
          page: page,
          query: afp_vars.query,
          category__in: categoryIDs, // Added the variable from the first AJAX call here as-is because it's working now
          offset: postOffset // Added the offset parameter with the variable to give it the value
        },
        success: function (res) {
          $(".filter-section").append(res);
          page += 1;
          postOffset += 9; // Added a counter to add 9 to the offset on success because I load in 9 posts every time the AJAX call runs
          loading = false; // This is important, but I forgot it last time around
        }
      })
    }
  }
});

Oh, and don’t forget (like I did) to go back and use your data for the offset parameter from the AJAX call into the functions.php file (in the second AJAX function, with the rest of the $args). Like so:

$args['offset'] = esc_attr( $_POST['offset'] );

Hope this helps somebody else. And if anyone has a critique of my code that could make it better, please add your input!