0

I hav ebeen trying to call two separate AJAX requests, on separate pages, each pulling in their respective parts. Right now, it only pulls in ONE of the AJAX requests on both pages even with specific IF page statements that technically should bar them from one another.

AJAX works on both pages it's being called on, however both pages are sharing the SAME AJAX call instead of their own separate call despite my efforts.

How can I can front-page.php to just call it's SPECIFIC AJAX call and category.php to just call it's own? Right now I have the code I feel should be doing that but only cat_loadmore_posts loads on both pages. I have tried making sure there are no shared function names which makes it all the more curious why it's doing it. I'm interested in finding out how to do this but also the reason behind it. Help is always appreciated.

front-page.php

<?php
$current_page = max( 1, get_query_var( 'paged' ) );
$the_query = new WP_Query( array(
    'cat'            => 5,
    'post_type'      => 'post',
    'posts_per_page' => 9,
    'post_status' => 'publish',
    'paged'          => $current_page,
) );

$_SESSION['count'] = 1;
wp_localize_script( 'my_loadmore', 'misha_loadmore_params', array(
    'ajaxurl'      => admin_url( 'admin-ajax.php', 'relative' ),
    'posts'        => json_encode( $the_query->query_vars ),
    'current_page' => $current_page,
    'max_page'     => $the_query->max_num_pages
) );
?>

<div id="main" class="container-fluid">
    <?php if ($the_query->have_posts()) : ?>
        <?php $count = 0; ?>
        <?php while ($the_query->have_posts()) : $the_query->the_post(); get_template_part( 'parts/content', get_post_format() ); ?>
        <?php $count++; $_SESSION['count']=$_SESSION['count']+1; ?>

<?php if ($count == 8 && is_active_sidebar('seriesbar2') ) : ?>
     <div class="post">
        <?php dynamic_sidebar('sidebar'); ?>
     </div>
<?php endif; ?>

<?php endwhile; ?>
<?php endif; ?>
<?php wp_reset_postdata(); ?>
<?php get_footer(); ?>
</div><!-- END CONTAINER -->

category.php

<?php
    $current_page = max( 1, get_query_var( 'paged' ) );
    $cat_query = new WP_Query( array(
        'posts_per_page' => 5, 
        'post_type'      => 'post',
        'category' => 14, 
        'post_status'=>'publish',
        'paged' => $current_page, 
        'order'=>'DESC' 
    ) );

    $_SESSION['count'] = 1;
    wp_localize_script( 'cat_loadmore', 'cat_loadmore_params', array(
        'ajaxurl'      => admin_url( 'admin-ajax.php', 'relative' ),
        'posts'        => json_encode( $cat_query->query_vars ),
        'current_page' => $current_page,
        'max_page'     => $cat_query->max_num_pages
    ) );        
?>

<div id="catfeed" class="container feed-container">     
<?php if ($cat_query->have_posts()) : ?>
    <?php $count = 0; ?>
    <?php while ($cat_query->have_posts()) : $cat_query->the_post(); get_template_part( 'parts/categorycontent', get_post_format() ); ?>
    <?php $count++; $_SESSION['count']=$_SESSION['count']+1; ?>
<?php endwhile; ?>
<?php endif; ?>
<?php wp_reset_postdata(); ?>
</div><!-- END CONTAINER -->

myloadmore.js - the AJAX call that doesn't work once I added the catloadmore.js - worked previously

jQuery(function($){
    var canBeLoaded = true,
        bottomOffset = 1300; 

    $(window).scroll(function(){
        if ( misha_loadmore_params.current_page >= misha_loadmore_params.max_page ) {
            return;
        }
        var data = {
            'action': 'loadmore',
            'query': misha_loadmore_params.posts,
            'page' : misha_loadmore_params.current_page
        };
        if( $(document).scrollTop() > ( $(document).height() - bottomOffset ) && canBeLoaded == true ){
            $.ajax({
                url : misha_loadmore_params.ajaxurl,
                data: data,
                type: 'POST',
                beforeSend: function( xhr ){
                    canBeLoaded = false;
                },
                success:function(data){
                    if( data ) {
                        $('#main').find('div.post:last-of-type').after( data );
                        canBeLoaded = true; 
                        misha_loadmore_params.current_page++;
                    }
                }
            });
        }
    });
});

catloadmore.js - This one works on category.php AND front-page.php even though I'm not calling it on front-page.php. I just want it to work on category.php

jQuery(function($){
    var canBeLoaded = true, 
    bottomOffset = 1300;

    $(window).scroll(function(){
        if ( cat_loadmore_params.current_page >= cat_loadmore_params.max_page ) {     
            return;
        }
        var data = {
            'action': 'loadmore',
            'query': cat_loadmore_params.posts,
            'page' : cat_loadmore_params.current_page
        };
        if( $(document).scrollTop() > ( $(document).height() - bottomOffset ) && canBeLoaded == true ){

            $.ajax({
                url : cat_loadmore_params.ajaxurl,
                data: data,
                type: 'POST',
                beforeSend: function( xhr ){
                    canBeLoaded = false;
                },
                success:function(data){
                    if( data ) {
                        $('#catfeed').find('div.catpost:last-of-type').after( data );
                        canBeLoaded = true;
                        cat_loadmore_params.current_page++;
                    }
                }
            });
        }
    });
});

functions.php

function misha_my_load_more_scripts() {
    if ( is_front_page() )
        {
            wp_register_script( 'my_loadmore', get_stylesheet_directory_uri() . '/js/myloadmore.js',
            array( 'jquery' ), '', true );
            wp_enqueue_script( 'my_loadmore' );
        }
}
add_action( 'wp_enqueue_scripts', 'misha_my_load_more_scripts' );

function cat_load_more_scripts() {
    if ( is_category() )
        {
            wp_register_script( 'cat_loadmore', get_stylesheet_directory_uri() . '/js/catloadmore.js',
            array( 'jquery' ), '', true );
            wp_enqueue_script( 'cat_loadmore' );
        }
}
add_action( 'wp_enqueue_scripts', 'cat_load_more_scripts' );


function register_my_session(){
    if( ! session_id() ) {
        session_start();
    }
}

add_action('init', 'register_my_session');

function cat_loadmore_ajax_handler() {
    $args = json_decode( wp_unslash( $_POST['query'] ), true );
    $args['paged'] = $_POST['page'] + 1; // load the next page

    $cat_query = new WP_Query( $args );

    if ( $cat_query->have_posts() ) :

        while ( $cat_query->have_posts() ) : $cat_query->the_post();

            $count = $_SESSION['count'];
            $_SESSION['count']=$_SESSION['count']+1;

            get_template_part( 'parts/categorycontent', get_post_format() );

        endwhile;
    endif;

    wp_die();
}
add_action( 'wp_ajax_loadmore', 'cat_loadmore_ajax_handler' );        // Authenticated users
add_action( 'wp_ajax_nopriv_loadmore', 'cat_loadmore_ajax_handler' ); // Non-authenticated users

function misha_loadmore_ajax_handler() {
    $args = json_decode( wp_unslash( $_POST['query'] ), true );
    $args['paged'] = $_POST['page'] + 1; // load the next page

    $the_query = new WP_Query( $args );

    if ( $the_query->have_posts() ) :

        while ( $the_query->have_posts() ) : $the_query->the_post();
            $count = $_SESSION['count'];
            $_SESSION['count']=$_SESSION['count']+1;

            get_template_part( 'parts/content', get_post_format() );

            <?php if ($count == 8 && is_active_sidebar('seriesbar2') ) : ?>
                <div class="series-container post second-series">

                    <?php dynamic_sidebar('seriesbar2'); ?>

                </div>
            <?php endif;
        endwhile;
    endif;

    wp_die();
}
add_action( 'wp_ajax_loadmore', 'misha_loadmore_ajax_handler' );        // Authenticated users
add_action( 'wp_ajax_nopriv_loadmore', 'misha_loadmore_ajax_handler' ); // Non-authenticated users

UPDATED CODE

Code after @SallyCJ first answer I left nothing out in the case of oversight on my behalf

category.php

<?php
        $current_page = max( 1, get_query_var( 'paged' ) );
        $category = get_category( get_query_var( 'cat' ) );
        $cat_id = $category->cat_ID;
        $change = 0;
        $cat_query = new WP_Query( array(
            'posts_per_page' => 5, 
            'post_type'      => 'post',
            'offset' => 4, 
            'category__in' => array($cat_id), 
            'post_status'=>'publish',
            'paged' => $current_page, 
            'order'=>'DESC' 
    ) );

    $_SESSION['count'] = 1;
    wp_localize_script( 'cat_loadmore', 'cat_loadmore_params', array(
        'ajaxurl'      => admin_url( 'admin-ajax.php', 'relative' ),
        'posts'        => json_encode( $cat_query->query_vars ),
        'current_page' => $current_page,
        'max_page'     => $cat_query->max_num_pages
    ) );        
?>
    <div id="catfeed" class="container-fluid">
            <?php if ($cat_query->have_posts()) : ?>
            <?php $count = 0; ?>
                <?php while ($cat_query->have_posts()) : $cat_query->the_post(); get_template_part( 'parts/categorycontent', get_post_format() ); ?>
                <?php 
                    $count++;
                    $_SESSION['count']=$_SESSION['count']+1;
                ?>
                <?php endwhile; ?>
            <?php endif; ?>
        <?php wp_reset_postdata(); ?>
    </div><!-- END CONTAINER -->

functions.php

function cat_load_more_scripts() {
    if ( is_category() )
        {
            wp_register_script( 'cat_loadmore', get_stylesheet_directory_uri() . '/js/catloadmore.js',
            array( 'jquery' ), '', true );
            wp_enqueue_script( 'cat_loadmore' );
        }
}
add_action( 'wp_enqueue_scripts', 'cat_load_more_scripts' );

add_action('init', 'register_my_session');

function cat_loadmore_ajax_handler() {
    $args = json_decode( wp_unslash( $_POST['query'] ), true );
    $args['paged'] = $_POST['page'] + 1; // load the next page

    $cat_query = new WP_Query( $args );

    if ( $cat_query->have_posts() ) :

        while ( $cat_query->have_posts() ) : $cat_query->the_post();

            $count = $_SESSION['count'];
            $_SESSION['count']=$_SESSION['count']+1;

            get_template_part( 'parts/categorycontent', get_post_format() );

        endwhile;
    endif;
    wp_die();
}
add_action( 'wp_ajax_catloadmore', 'cat_loadmore_ajax_handler' );        // Authenticated users
add_action( 'wp_ajax_nopriv_catloadmore', 'cat_loadmore_ajax_handler' ); // Non-authenticated users

function misha_loadmore_ajax_handler() {
    $args = json_decode( wp_unslash( $_POST['query'] ), true );
    $args['paged'] = $_POST['page'] + 1; // load the next page

    $the_query = new WP_Query( $args );

    if ( $the_query->have_posts() ) :

        while ( $the_query->have_posts() ) : $the_query->the_post();
            $count = $_SESSION['count'];
            $_SESSION['count']=$_SESSION['count']+1;

            get_template_part( 'parts/content', get_post_format() );
              if ($count == 4 && is_active_sidebar('seriesbar1') ) : ?>
                <div class="series-container post first-series">

                    <?php dynamic_sidebar('seriesbar1'); ?>

                </div>

            <?php endif; ?>

            <?php if ($count == 8 && is_active_sidebar('seriesbar2') ) : ?>
                <div class="series-container post second-series">

                    <?php dynamic_sidebar('seriesbar2'); ?>

                </div>
            <?php endif; ?>

            <?php if ($count == 12 && is_active_sidebar('seriesbar3') ) : ?>
                <div class="series-container post third-series">

                    <?php dynamic_sidebar('seriesbar3'); ?>

                </div>
            <?php endif; ?>

            <?php if ($count == 16 && is_active_sidebar('seriesbar4') ) : ?>
                <div class="series-container post fourth-series">

                    <?php dynamic_sidebar('seriesbar4'); ?>

                </div>
            <?php endif; ?>

            <?php if ($count == 20 && is_active_sidebar('seriesbar5') ) : ?>
                <div class="series-container post fifth-series">

                    <?php dynamic_sidebar('seriesbar5'); ?>

                </div>
            <?php endif; ?>

            <?php if ($count == 24 && is_active_sidebar('seriesbar6') ) : ?>
                <div class="series-container post sixth-series">

                    <?php dynamic_sidebar('seriesbar6'); ?>

                </div>
            <?php endif; ?>

            <?php if ($count == 28 && is_active_sidebar('seriesbar7') ) : ?>
                <div class="series-container post seventh-series">

                    <?php dynamic_sidebar('seriesbar7'); ?>

                </div>
            <?php endif; ?>

            <?php if ($count == 32 && is_active_sidebar('seriesbar8') ) : ?>
                <div class="series-container post eighth-series">

                    <?php dynamic_sidebar('seriesbar8'); ?>

                </div>
            <?php endif;
        endwhile;
    endif;

    wp_die();
}

add_action( 'wp_ajax_myloadmore', 'misha_loadmore_ajax_handler' );        // Authenticated users
add_action( 'wp_ajax_nopriv_myloadmore', 'misha_loadmore_ajax_handler' ); // Non-authenticated users

catloadmore.js

jQuery(function($){
var canBeLoaded = true, 
bottomOffset = 1300;

$(window).scroll(function(){
    if ( cat_loadmore_params.current_page >= cat_loadmore_params.max_page ) {     
        return;
    }
    var data = {
        'action': 'catloadmore', // <- same as above action
        'query': cat_loadmore_params.posts,
        'page' : cat_loadmore_params.current_page
    };
    if( $(document).scrollTop() > ( $(document).height() - bottomOffset ) && canBeLoaded == true ){

        $.ajax({
            url : cat_loadmore_params.ajaxurl,
            data: data,
            type: 'POST',
            beforeSend: function( xhr ){
                canBeLoaded = false;
            },
            success:function(data){
                if( data ) {
                    $('#catfeed').find('div.catpost:last-of-type').after( data );
                    canBeLoaded = true;
                    cat_loadmore_params.current_page++;
                }
            }
        });
    }
});

});

categorycontent.php - the content being loaded in, truncated for clarity (also just testing this block of code for consistency)

<div class="feed-container row mx-auto align-items-center catpost">  
    <div class="col-sm-5">
        <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail( 'thumbnail', array( 'class' => 'img-fluid' ) ); ?></a>
    </div>

    <div class="col-sm-7 mx-auto">
        <h3><a class="align-middle" href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
    </div>
</div><!-- END ROW -->
2
  • Have you already checked the answer? Did it help?
    – Sally CJ
    Commented Apr 25, 2019 at 3:35
  • @SallyCJ ironic, I'm actually in the middle of testing the answer right now. I will reply to this within a few minutes Commented Apr 25, 2019 at 3:36

1 Answer 1

1

I'm interested in finding out how to do this but also the reason behind it.

I haven't tested your code (the conditional stuff), but from what I could see:

The Reason

The AJAX action is the same for both the front page and category AJAX requests:

  1. myloadmore.js

    var data = {
        'action': 'loadmore', // <- same as below action
        'query': misha_loadmore_params.posts,
        'page' : misha_loadmore_params.current_page
    };
    
  2. catloadmore.js

    var data = {
        'action': 'loadmore', // <- same as above action
        'query': cat_loadmore_params.posts,
        'page' : cat_loadmore_params.current_page
    };
    

And in functions.php, there are two callbacks (cat_loadmore_ajax_handler and misha_loadmore_ajax_handler) hooked to the AJAX action named loadmore. These callbacks would both be called when an AJAX request was made where the action is loadmore, no matter the request came from the front page or a category archive.

But you call wp_die() (which is similar to calling die or exit) from within the callbacks, so once the cat_loadmore_ajax_handler() is called, the other callback will not going to run since the script execution has ended. So that's why:

catloadmore.js - This one works on category.php AND front-page.php even though I'm not calling it on front-page.php.

The "How To" (fix the issue)

Use different actions:

  1. myloadmore.js

    var data = {
        'action': 'myloadmore',
        ...
    };
    
  2. catloadmore.js

    var data = {
        'action': 'catloadmore',
        ...
    };
    

And in functions.php:

  1. For the front page:

    // AJAX action: myloadmore
    add_action( 'wp_ajax_myloadmore', 'misha_loadmore_ajax_handler' );        // Authenticated users
    add_action( 'wp_ajax_nopriv_myloadmore', 'misha_loadmore_ajax_handler' ); // Non-authenticated users
    
  2. For category pages:

    // AJAX action: catloadmore
    add_action( 'wp_ajax_catloadmore', 'cat_loadmore_ajax_handler' );        // Authenticated users
    add_action( 'wp_ajax_nopriv_catloadmore', 'cat_loadmore_ajax_handler' ); // Non-authenticated users
    
6
  • I tried this, but it didn't work. The front page loads and loads the correct AJAX but now the category doesn't load AJAX at all.I don't see any console errors. Please let me know if I can provide anything else. Thanks! Commented Apr 25, 2019 at 4:09
  • Can you update the question with your current code? And I just noticed that you're including the sidebar in the AJAX response (dynamic_sidebar('sidebar');) - why? Also, there's actually a syntax error in the misha_loadmore_ajax_handler() - there should be a ?> after the get_template_part( 'parts/content', get_post_format() );.
    – Sally CJ
    Commented Apr 25, 2019 at 5:09
  • I updated the question as requested. The AJAX response dynamic sidebar is a bit complicated but it works for the misha request (long story short, the sidebars interject in posts) for clarity's sake I've included it in the question so you have a full view. It's not necessary for catloadmore so I don't use it there. Commented Apr 25, 2019 at 5:57
  • I've tested your code, and after using different actions, everything worked fine for me. So try using the exact code in the original question and simply change the actions, and see if that helps.
    – Sally CJ
    Commented Apr 25, 2019 at 9:33
  • 1
    Your suggestion made me realize at some point I must have accidentally deleted my footer php causing JS to not load as it should. Once I solved this and added your changes on action it worked perfectly! You're amazing thank you! Commented Apr 25, 2019 at 16:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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