questions

Ajax/Jquery/PHP issue when trying to load the posts on page scroll

Rate this post

I am trying to load my posts using Ajax on my word press website. Everything works fine except few. I have setup the ajax call when a users reaches 2000px above the footer, now the issue is that once the user reach at that point ajax function is called again and again until the new post loads via ajax what I need is to call the ajax function once only when the user reached at that point then the posts should load then again the user scroll down and reaches at that point and ajax function should be called once each time. Also each time I have setup the (3) number of posts to load every time same posts load again n again. Below is my code

PHP Code

function ajax_load_posts($args) {
    $ajax = false;
    if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
        strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
        $ajax = true;
    }
    $post-per-page =3;
    $pagination = $_POST['page'] + 1;
    $args = array(
        'post_type' => 'post',
        'post_status' => 'publish',
        'order' => 'DESC'
        'orderby'   => 'title',
        'posts_per_page' =>$post-per-page,
        'paged'=>$pagination
    );
    $query = new WP_Query($args);
    if ($query->have_posts()):
        while ($query->have_posts()): $query->the_post();
            include 'ajax-content.php';
        endwhile;
    else:
        echo "false";
    wp_reset_postdata();
    if($ajax) die();
}

Javascript/jQuery code

jQuery(document).ready(function($) {
    $(window).scroll(function() {
        var that = $('#loadMore');
        var page = $('#loadMore').data('page');
        var newPage = page + 1;
        var ajaxurl = $('#loadMore').data('url');
        var bottomOffset = 2000; 
        if( $(document).scrollTop() > ( $(document).height() - bottomOffset )){
            $.ajax({
                url: ajaxurl,
                type: 'post',
                data: {
                    page: page,
                    action: 'ajax_load_posts'
                },
                error: function(response) {
                    console.log(response);
                },
                success: function(response) {
                    if (response == 0) {
                        if ($("#no-more").length == 0) {
                            $('#ajax-content').append('<div id="no-more" class="text-center"><p>No more posts to load.</p></div>');
                        }
                        $('#loadMore').hide();
                    } else {
                        $('#loadMore').data('page', newPage);
                        $('#ajax-content').append(response);
                    }
                }
            });
        }
    });
});

 

✔️Solution:

You need to track when your making the request like below:

function ajax_load_posts($args) {
    $ajax = false;
    if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
        strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
        $ajax = true;
    }

    // camel case is more excepted in WP/PHP for var names
    $posts_per_page = 3;

    // no need to increment here that is handled by js
    $pagination = $_POST['page'];

    $args = array(
        'post_type' => 'post',
        'post_status' => 'publish',
        'order' => 'DESC'
        'orderby'   => 'title',
        'posts_per_page' => $posts_per_page,
        'paged'=>$pagination
    );
    $query = new WP_Query($args);
    if ($query->have_posts()):
        while ($query->have_posts()): $query->the_post();
            include 'ajax-content.php';
        endwhile;
    else:
        echo "false";
    wp_reset_postdata();
    if($ajax) die();
}
jQuery(document).ready(function($) {
    // grab/set these on load rather that each scroll
    var page = $('#loadMore').data('page');
    var ajaxurl = $('#loadMore').data('url');
    var bottomOffset = 2000;

    // track if already fetching
    var isFetching = false;

    $(window).scroll(function() {
        // is this needed
        var that = $('#loadMore');

        // added check for isFetching
        if( $(document).scrollTop() > ( $(document).height() - bottomOffset ) && ! isFetching){
            // update so we dont keep calling
            isFetching = true;
            $.ajax({
                url: ajaxurl,
                type: 'post',
                data: {
                    page: page,
                    action: 'ajax_load_posts'
                },
                error: function(response) {
                    console.log(response);
                },
                success: function(response) {
                    if (response == 0) {
                        if ($("#no-more").length == 0) {
                            $('#ajax-content').append('<div id="no-more" class="text-center"><p>No more posts to load.</p></div>');
                        }
                        $('#loadMore').hide();

                        // update so the next time user hits scroll point we can fetch
                        isFetching = false;

                        // update page no need to set a new var and only if we get results
                        page++; 
                    } else {
                        $('#loadMore').data('page', newPage);
                        $('#ajax-content').append(response);
                    }
                }
            });
        }
    });
});

Leave a Reply

Your email address will not be published.

Back to top button