0

I'm trying to load posts via AJAX, but while the code below works on page load, after the initial 8 posts, the return is everything. This doesn't seem to make sense as to why on page load it would work, then subsequent requests are then returning so many results.

The query is for multiple categories of the same post type, the category ID is obtained when clicking a tab (which works fine):

var cat = jQuery(this).attr("id");

Is there something obvious I'm missing here?

// HTML

<div class="aj_load">Loading...</div>
<div id="data"></div>

// AJAX Posts (on the page)

    var pageNumber = '1';

    function load_posts(){

       var cat = jQuery("#tabs li.active").attr("id");   
       jQuery(".aj_load").animate({'opacity' : 1}, 300);

       pageNumber++;
       var str = '&cat=' + cat + '&pageNumber=' + pageNumber + '&action=load_more';
       jQuery.ajax({
          type: "POST",
          dataType: "html",
          url: ajaxurl,
          data: str,
          success: function(data){
             var jQuerydata = jQuery(data);
             if(jQuerydata.length){
                jQuery(".aj_load").animate({'opacity' : 0}, 300);
                jQuery("#data").append(jQuerydata); 
             }

            },
            error : function(jqXHR, textStatus, errorThrown) {
                jQueryloader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
            }

        });
        return false;
    }

    // Run load_posts() on document load
        jQuery(document).ready(function(){
            load_posts();
        });

    // Run load_posts() on scroll
    jQuery(document).on('scroll', function() {
       var distanceFromBottom = Math.floor(jQuery(document).height() - jQuery(document).scrollTop() - jQuery(window).height());

   if(distanceFromBottom < 400) {
      load_posts();
   }

});

// AJAX Load More Function (in functions.php)

function load_more(){

   $cat = $_REQUEST['cat'];
    $page = $_POST['pageNumber'];

    header("Content-Type: text/html");

    $args = array(
      'cat' => $cat,
      'post_type' => 'post',
      'orderby' => 'date',
      'order' => 'DESC',
        'suppress_filters' => true,
        'posts_per_page' => 8,
        'paged' => $page,
    );

    $loop = new WP_Query($args);

    if ($loop -> have_posts()) : while ($loop -> have_posts()) : $loop -> the_post();

        locate_template('/parts/news-loop.php', TRUE, FALSE);

    endwhile; else :

      echo "No More Posts";

    endif;
    wp_reset_postdata();
    die();
}

add_action('wp_ajax_nopriv_load_more', 'load_more');
add_action('wp_ajax_load_more', 'load_more');

// The loop template

<?php

    $cats = get_the_category();
    $cat_slug = $cats[0]->slug;

?>

<div class="news-post">

    <h2><?php the_title(); ?> - <?php the_time('dS F Y') ;?></h2>

    <div class="news-line"></div>
    <div class="news-hex <?php echo $cat_slug; ?>"></div>

    <div class="text">

    <p><?php echo wp_trim_words(get_the_content(), 40, '...') ?></p>

        <a class="more" href="<?php the_permalink(); ?>">FIND OUT MORE</a>

    </div>

    <div class="clear"></div>

</div>
0

OK, so I'm not sure if this is best practice, but after testing the code by using a onclick rather than scroll, the pages do load appropriately. I have got round the issue of loads of results by adding a condition to only return true after the AJAX has completed;

// AJAX Posts
var pageNumber = '0';
pauseAJAX = 'yes';

function load_posts(){

   var cat = jQuery("#tabs li.active").attr("id");   
   jQuery(".aj_load").animate({'opacity' : 1}, 300);

   pauseAJAX = 'yes';

       pageNumber++;
    var str = '&cat=' + cat + '&pageNumber=' + pageNumber + '&action=load_more';
    jQuery.ajax({
        type: "POST",
        dataType: "html",
        url: ajaxurl,
        data: str,
        success: function(data){
         var jQuerydata = jQuery(data);
         if(jQuerydata.length){

         jQuery(".aj_load").animate({'opacity' : 0}, 300);
         jQuery("#data").append(jQuerydata);
         pauseAJAX = 'no';   

      }
        },
        error : function(jqXHR, textStatus, errorThrown) {
         jQueryloader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
        }

    });
    return false;
}



jQuery(window).scroll(function(){
   if(jQuery(window).scrollTop() + 400 > jQuery(document).height() - jQuery(window).height() ){
      if(pauseAJAX == 'no') {
         load_posts();
      };
   };
})

;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.