When calling wp_query via AJAX and passing a category ID and search parameter, the query does not return any posts. On page load, the query runs fine, which runs the same query.

If I add these variables directly in the JS or on the query itself, the query also runs fine.

I can also see the variables being set on the JS console when tested, so the issue would appear to be that they are not being passed via the AJAX request, but I’m struggling to see why as this runs on page load.

The “cat” variable is set by selecting a category (or multiple ones) via a side menu, then this is set as a string of IDs (1,2,3,4). The “0” value is set initially, so all posts are returned.

The “search” variable is taken from an input field.

Here is my JS;

// Set the inital Page Number To Zero
var pageNumber = 0;

    // Main AJAX Function
    function ajaxCaseStudies() {

        // Fade In Loading
        $("#loading").delay(300).fadeIn(300);

        // Get Varribles For Query
        cat = $("ul.mobMenu li.active").map(function () { return $(this).attr('data-id'); }).get();
        search = $("input#s").val();

        // Pause the AJAX Request
        pauseAJAX = 'yes';

        // Increment The Page Number Varrible
        pageNumber++;

        // Send Data To Query   
        $.ajax({
            url: ajaxurl + '?action=ajaxCaseStudies&cat="+cat+"&search="+search+"&pageNumber="+pageNumber,

            success: function(data){
                var result = $(data);
                if(result.length){
                    $("#case-studies").append(result);
                    $("#loading').fadeOut(300);
                    $("#case-studies").delay(300).fadeIn(300);
                    pauseAJAX = 'no';   
                } else {
                    $('#loading').fadeOut(300);
                    $("#case-studies").append('<h4 class="inner center">No more results</h4>');
                    $("#case-studies").delay(300).fadeIn(300);
                    pauseAJAX = 'yes';
                }
            }
        });

    }

// Run On Page Load
$(document).ready(function(){
    ajaxCaseStudies();  
});

// Setup Scroll Function
$(window).on('resize',scrollFunction);
$(document).bind("ready", function() {
    scrollFunction();
});

// Set The Height Varrible Depeding On Screen Size
function scrollFunction() {
    if($(window).width() >= 990) {
        theHeight = 500;
    } else if($(window).width() <= 990) {
        theHeight = 800;
    }       
};

// Run The Function On Scroll   
$(window).scroll(function(){
    if($(window).scrollTop() + theHeight > $(document).height() - $(window).height() ){
        if(pauseAJAX == 'no') {
            ajaxCaseStudies();
        };
    };
});

// Run On Category Click
$('ul.mobMenu li').click(function(){
    if($(this).attr('data-id') != 0) {
        $(this).toggleClass('active');
        $('ul.mobMenu li#all').removeClass('active');
        $("#case-studies").fadeOut(300).html('');
        ajaxCaseStudies();
    } else {
        $('ul.mobMenu').children().removeClass('active');
        $('ul.mobMenu li#all').addClass('active');
        $("#case-studies").fadeOut(300).html('');
        ajaxCaseStudies();
    }
})

// Run On Search Icon Click
$('.s_icon').click(function(){
    $("#case-studies").fadeOut(300).html('');
    ajaxCaseStudies();
})

// Run On Search Return
$(document).keyup(function (e) {
    if (e.keyCode == 13) {
        $("#case-studies").fadeOut(300).html('');
        ajaxCaseStudies();
    }
});

and the query from functions.php:

// Load Posts
function ajaxCaseStudies() {

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

    if($cat == 0) {

        $args = array(
            'post_type' => 'case_studies',
            'post_status' => 'publish',
            'orderby' => 'date',
            'order' => 'ASC',
            'suppress_filters' => true,
            'posts_per_page' => 8,
            's' => $search,
            'paged' => $page
        );

    } else {

        $args = array(
            'tax_query' => array(
                array(
                    'taxonomy' => 'case_studies_categories',
                    'terms' => array($cat),
                    'field' => 'term_id'
                )
            ),
            'post_type' => 'case_studies',
            'post_status' => 'publish',
            'orderby' => 'date',
            'order' => 'ASC',
            'suppress_filters' => true,
            'posts_per_page' => 8,
            's' => $search,
            'paged' => $page
        );

    }

    $loop = new WP_Query($args);

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

        locate_template('/assets/snippets/case-studies-loop.php', TRUE, FALSE);

    endwhile; endif;
    wp_reset_postdata();
    die();

}

add_action('wp_ajax_nopriv_ajaxCaseStudies','ajaxCaseStudies');
add_action('wp_ajax_ajaxCaseStudies','ajaxCaseStudies');

I hope all of the above makes sense. Please let me know if there’s any further info required.

0

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *