0

Kinda stuck here working with AJAX and trying to show posts based on user interaction. Right now I have it working where user makes a category dropdown selection and the posts load accordingly. What I would like to do is take it one step further and populate another drop-down with subcategories based on the parent category that was selected. View the site here.

jQuery

$('#ajaxFilter select').on('change', function(event) {
if(event.preventDefault) { event.preventDefault(); }
$this = $(this);
$value = this.value;
$page = $this.data('page');
$term = $this.data('term');
$qty = $this.closest('#ajaxFilter').data('paged')

    $params = {
        //Bind parameters
        'value': $value,
        'page' : $page,
        'term' : $term,
        'qty'  : $qty,
    };

    //Run the query with those parameters
    get_posts($params);
});



function get_posts($params) {
$content   = $('#ajaxPosts');
$.ajax({
    url: psc.ajax_url,
    data: {
        action: 'filter_posts',
        nonce: psc.nonce,
        params: $params
    },
    type: 'post',
    dataType: 'json',
success: function(data, textStatus, XMLHttpRequest) {
    if (data.status === 200) {
        $content.html(data.content);
    }
    else if (data.status === 201) {
        $content.html(data.message);    
    }
    else {
        $status.html(data.message);
    }
    },
error: function(MLHttpRequest, textStatus, errorThrown) {
    $status.html(textStatus);
     }
});

}

functions.php

function psc_filter_posts() {
if( !isset( $_POST['nonce'] ) || !wp_verify_nonce( $_POST['nonce'], 'psc' ) )
die('Permission denied');

$value = intval($_POST['params']['value']);;
$term = sanitize_text_field($_POST['params']['term']);
$page = intval($_POST['params']['page']);
$qty  = intval($_POST['params']['qty']);

if ( $value == 0 ) : 
    $tax_qry[] = [
        'taxonomy' => 'category',
        'field'    => 'term_id',
        'terms'    => $value,
        'operator' => 'NOT IN'
    ];
else :
    $tax_qry[] = [
        'taxonomy' => 'category',
        'field'    => 'term_id',
        'terms'    => $value,
    ];
 endif;

//Setup the query args for wp query
$args = [
'paged'          => $page,
'post_status'    => 'publish',
'posts_per_page' => $qty,
'tax_query'      => $tax_qry
];

$qry = new WP_Query($args);

ob_start();
if ($qry->have_posts()) : ?>
    <div class="container">
            <?php while ($qry->have_posts()) : $qry->the_post(); ?>

            LOOP STUFF              

            <?php endwhile; ?>
    </div><!-- .container -->

    <nav class = "container mt-5 text-center">
        <div class="row">
            <div class="col-sm-12">
                <?php psc_ajax_pager($qry,$page,$value); ?>
            </div><!-- .col-sm-12 -->
        </div><!-- .row -->
    </nav>

<?php $response = [
'status'=> 200,
'found' => $qry->found_posts
];
else :
$response = [
    'status'  => 201,
    'message' => 'No posts found'
];

endif;

$response['content'] = ob_get_clean();

die(json_encode($response));

}

add_action('wp_ajax_filter_posts', 'psc_filter_posts');
add_action('wp_ajax_nopriv_filter_posts', 'psc_filter_posts');
0

Eureka! So I ended up just adding in a second ajax call into the function. For some reason it's returning successful but not with a 200 response. Anyway, it's working. If anyone knows why it's returning an unknown response (besides 200 or 201) please share. Thanks!

function get_posts($params) {
    $.ajax({
        url: psc.ajax_url,
        data: {
            action: 'get_subcats',
            nonce: psc.nonce,
            params: $params
        },
        type: 'post',
        dataType: 'json',
        success: function(data, textStatus, XMLHttpRequest) {
            if (data.status === 200) {
            }
            else if (data.status === 201) {
                alert('201');
                $content.html(data.message);    
            }
            else {
                $('#subcategories').empty();
                $('#subcategories').append(data.content);
            }
        },
        error: function(MLHttpRequest, textStatus, errorThrown) {
            $status.html(textStatus);
        }
        });

        $.ajax({
        url: psc.ajax_url,
        data: {
            action: 'filter_posts',
            nonce: psc.nonce,
            params: $params
        },
        type: 'post',
        dataType: 'json',
        success: function(data, textStatus, XMLHttpRequest) {
            if (data.status === 200) {
                $('#ajaxPosts').html(data.content);
            }
            else if (data.status === 201) {
                $content.html(data.message);    
            }
            else {
                $status.html(data.message);
            }
        },
        error: function(MLHttpRequest, textStatus, errorThrown) {
            $status.html(textStatus);
        }
    });
}

functions.php

function psc_subcategories() {
if( !isset( $_POST['nonce'] ) || !wp_verify_nonce( $_POST['nonce'], 'psc' ) )
die('Permission denied');

$value = intval($_POST['params']['value']);;

ob_start();

$categories=  get_categories('child_of='.$value.'&hide_empty=1');
      foreach ($categories as $cat) {
        $option .= '<option value="'.$cat->term_id.'">';
        $option .= $cat->cat_name;
        $option .= ' ('.$cat->category_count.')';
        $option .= '</option>';
      }
    echo '<option value="-1" selected="selected">Subcategory</option>'.$option;

$response['content'] = ob_get_clean();

die(json_encode($response));

}

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.