0

I've been following this tutorial for a simple AJAX filter search within wordpress:

https://itsmereal.com/simple-ajax-filter-search-for-wordpress/?unapproved=3915&moderation-hash=039ff3c1d56b57d1456ededcfa5ea219#comment-3915

I've added some checkboxes into my form for the user to select one or more categories (custom taxonomy) to search the custom post type (courses)

if I search for something that exists, the checkbox filters work fine, but if I search for something I know doesn't exist, It does nothing and I just get a 200 code in XHR in inspector.

note: I tried deleting the wp_die(); function within the Ajax callback, this makes the no result message come up if the query yields no results, however if the query will yield results, nothing happens.

Here's my code in full

functions.php

// Scripts for Ajax Filter Search

function my_ajax_filter_search_scripts() {
    wp_enqueue_script( 'my_ajax_filter_search', get_stylesheet_directory_uri(). '/js/search-script.js', array(), '1.0', true );
        wp_localize_script( 'my_ajax_filter_search', 'jsData',[
        'ajaxUrl' => admin_url('admin-ajax.php'),
    ]);
}

// Shortcode: [my_ajax_filter_search]
function my_ajax_filter_search_shortcode() {

    my_ajax_filter_search_scripts(); // Added here

    ob_start(); ?>

        <div id="my-ajax-filter-search" class="text-left">
        <form action="" method="get">

            <input type="text" name="search" class="quicksearch mb-4" id="search-input" value="" placeholder="Search for a course..."><br>
                        <div class=" btn-group-toggle" data-toggle="buttons">

                            <?php
                            // Get the custom taxonomy's terms
                            $terms = get_terms(
                                array(
                                    'taxonomy'   => 'course_category',
                                    'hide_empty' => false,
                                )
                            );

                            // Check if any term exists
                            if ( ! empty( $terms ) && is_array( $terms ) ) {
                                // Run a loop and print them all
                                foreach ( $terms as $term ) { ?>
                                    <?php echo '<label class="btn btn-outline-secondary">
                                    <input type="checkbox" id="category" name="category" value="' . $term->slug . '">' . $term->name . '</label>'; ?>
                                    <?php
                                }
                            }
                            ?>

                    </div><br>
            <input class="btn btn-primary" type="submit" id="submit" name="submit" value="Search">
        </form>

    </div>

    <?php
    return ob_get_clean();
}

add_shortcode ('my_ajax_filter_search', 'my_ajax_filter_search_shortcode');


// Ajax Callback

add_action('wp_ajax_my_ajax_filter_search', 'my_ajax_filter_search_callback');
add_action('wp_ajax_nopriv_my_ajax_filter_search', 'my_ajax_filter_search_callback');

function my_ajax_filter_search_callback() {

    header("Content-Type: application/json");

    $meta_query = array('relation' => 'AND');

    if(isset($_GET['year'])) {
        $year = sanitize_text_field( $_GET['year'] );
        $meta_query[] = array(
            'key' => 'year',
            'value' => $year,
            'compare' => '='
        );
    }

    if(isset($_GET['rating'])) {
        $rating = sanitize_text_field( $_GET['rating'] );
        $meta_query[] = array(
            'key' => 'rating',
            'value' => $rating,
            'compare' => '>='
        );
    }

    if(isset($_GET['language'])) {
        $language = sanitize_text_field( $_GET['language'] );
        $meta_query[] = array(
            'key' => 'language',
            'value' => $language,
            'compare' => '='
        );
    }

    $tax_query = array();

        if(isset($_GET['catNames'])) {
            $catNames = $_GET['catNames'];
                error_log( 'MY STUFF var $catNames: ' . print_r( $catNames, true ) );
            foreach( $catNames as $catName ) {
                $tax_query[] = array(
                    'taxonomy'   => 'course_category',
                                'field' => 'slug',
                    'terms' => $catNames,
                );
            }
        }

    $args = array(
        'post_type' => 'courses',
        'posts_per_page' => -1,
        'meta_query' => $meta_query,
        'tax_query' => $tax_query
    );

    if(isset($_GET['search'])) {
        $search = sanitize_text_field( $_GET['search'] );
        $search_query = new WP_Query( array(
            'post_type' => 'courses',
            'posts_per_page' => -5,
            'meta_query' => $meta_query,
            'tax_query' => $tax_query,
            's' => $search
        ) );

                //error_log( 'MY STUFF var $search_query: ' . print_r( $search_query, true ) );

    }

        else {
        $search_query = new WP_Query( $args );
    }

        error_log( 'MY STUFF: ' . print_r( $tax_query, true ) );

    if ( $search_query->have_posts() ) {

        $result = array();

        while ( $search_query->have_posts() ) {
            $search_query->the_post();

            $cats = strip_tags( get_the_category_list(", ") );
            $result[] = array(
                "id" => get_the_ID(),
                "title" => get_the_title(),
                "content" => get_the_content(),
                "permalink" => get_permalink(),
                "year" => get_field('year'),
                "rating" => get_field('rating'),
                "director" => get_field('director'),
                "language" => get_field('language'),
                "coursecats" => $cats,
                "imageUrl" => wp_get_attachment_url(get_post_thumbnail_id(get_the_ID()),'full')
            );
        }
        wp_reset_query();

        echo json_encode($result);

    } else {
        // no posts found
    }

    wp_die();

}

search-script.js

$ = jQuery;

var mafs = $("#my-ajax-filter-search");
var mafsResults = $("#my-ajax-filter-search-results");
var mafsForm = mafs.find("form");

mafsForm.submit(function(e){
    e.preventDefault();

   console.log("form submitted");

    if(mafsForm.find("#search-input").val().length !== 0) {
    var search = mafsForm.find("#search-input").val();
}

//console.log('search:', search);

var catNames = [];
$.each($("input[name='category']:checked"), function(){
    catNames.push($(this).val());
});

console.log('cats :', catNames);

var data = {
    action : "my_ajax_filter_search",
    search : search,
    catNames: catNames
}

$.ajax({
        url : jsData.ajaxUrl,
        data : data,
        success : function(response) {
            mafsResults.find("div.results").empty();
            //$('.pagination').hide();
            if(response) {
                for(var i = 0 ;  i < response.length ; i++) {
                     var html  = "<div class='col-md-4' id='course-" + response[i].id + "'>";
                         html += "  <a href='" + response[i].permalink + "' title='" + response[i].title + "'>";
                         html += "      <img src='" + response[i].imageUrl + "' alt='" + response[i].title + "' />";
                         html += "      <div class='movie-info'>";
                         html += "          <h4>" + response[i].title + "</h4>";
                         html += "      </div>";
                         html += "  </a>";
                         html += "</div>";
                     mafsResults.find("div.results").append(html);
                }
            } else {
              mafsResults.find("div.results").empty();
                var html  = "<div class='no-result'>No matching movies found. Try a different filter or search keyword</div>";
                mafsResults.find("div.results").append(html);
            }

        }
    });

});

Template File

<div class="filters">
    <?php echo do_shortcode('[my_ajax_filter_search]'); ?>
</div>


<div id="my-ajax-filter-search-results">

    <?php
        $args = array(
            'post_type' => 'courses',
            'posts_per_page' => 16
        );

        $default_query = new WP_Query( $args );
        if ( $default_query->have_posts() ) {
            echo '<div class="results row">';
            while ( $default_query->have_posts() ) {
                $default_query->the_post();
                ?>
                        
                                <div class="col-md-4 mb-4 mb-md-3">
                                    <a class="home-image-link" href="<?php the_permalink(); ?>">
                                        <div class="link-image">
                                            <div style="background:url('<?php echo get_the_post_thumbnail_url(); ?>') center center no-repeat; background-size:cover; min-height:200px;">
                                            </div>
                                            <span class="bg-primary text-light mt-1 p-2 full-width d-inline-block">
                                                <?php the_title(); ?> <span class="float-right"><img src="/wp-content/themes/allintraining/img/chevron-right.svg" style="height:15px;" alt="chevron right"></span>
                                            </span>
                                        </div>
                                    </a>
                                </div>

                        <?php
            }
            wp_reset_postdata();
            echo '</div>';
        }
    ?>
</div>

Any help would be gratefully received, thanks in advance!

2
  • Your JS is checking for an empty response, but the response is never empty, because you're using wp_die, which is a response. Try using die() instead, or even better actually return some specific failure response.
    – vancoder
    Jul 16, 2021 at 16:16
  • @vancoder Thank you for your feedback, I've just tried using die() but it does the same thing, in the tutorial I worked this up from, they used wp_die() in the same manner and theirs works with that, any ideas what else could cause it?
    – Eland
    Jul 17, 2021 at 5:04

1 Answer 1

1

Managed to fix this, as @vancoder mentioned that the wp_die was causing there to still be a response and said to use die() instead. This didn't work, so instead I changed the way the json was sent. By using wp_send_json() uinstead, we don't need to use die() or wp_die() at the end of the function as wp_send_json() includes wp_die() within it. which all seems to work well.

update the callback in functions.php

    if ( $search_query->have_posts() ) {

        $result = array();

        while ( $search_query->have_posts() ) {
            $search_query->the_post();

            $cats = strip_tags( get_the_category_list(", ") );
            $result[] = array(
                "id" => get_the_ID(),
                "title" => get_the_title(),
                "content" => get_the_content(),
                "permalink" => get_permalink(),
                "year" => get_field('year'),
                "rating" => get_field('rating'),
                "director" => get_field('director'),
                "language" => get_field('language'),
                "coursecats" => $cats,
                "imageUrl" => wp_get_attachment_url(get_post_thumbnail_id(get_the_ID()),'full')
            );
        }
        wp_reset_query();

        //echo json_encode($result); - Old way
                wp_send_json($result); // new way (includes wp_die())

    } else {

    }

}

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.