Using AJAX to update woocommerce product grid

I have a Custom Visual composer element which displays a grid of woocommerce products and a list of the categories above that grid.

I want to be able to click on one of the category links and have it update the grid via ajax, but i cant seem to get my head around it.

Heres the code for the visual composer element :

// Product Grid
function productgrid_func( $atts ) {

ob_start();

 extract( shortcode_atts( array(
  'nanook_extra_class' => '',
 ), $atts ) );

 $params = array(
         'posts_per_page' => 8,
         'post_type' => 'product'
         //'product_cat' => 'hoodies'
 );
 $wc_query = new WP_Query($params);

 if ($wc_query->have_posts()) : ?>
        <div class="et-product-cats">

            <?php $wcatTerms = get_terms('product_cat', 
array('hide_empty' => 0, 'orderby' => 'ASC',  'parent' =>0));
                            foreach($wcatTerms as $wcatTerm) :
                            ?>
                                    <a class="cat-trigger" href="<?php 
echo get_term_link( $wcatTerm->slug, $wcatTerm->taxonomy ); ?>"><?php 
echo $wcatTerm->name; ?></a>
                            <?php endforeach; ?>
        </div>

        <ul class="products">
        <?php
        while ($wc_query->have_posts()) :
                 $wc_query->the_post();?>

                 <?php $output .= wc_get_template_part( 'content', 'product' ); ?>

 <?php endwhile;
 ?></ul>

 <?php
 wp_reset_postdata();
 else:  ?>
 <p>
      <?php _e( 'No Products' ); // (6) ?>
 </p>
 <?php endif;

    echo $output;

$myvariable = ob_get_clean();
    return $myvariable;

}


add_shortcode( 'productgrid', 'productgrid_func' );
add_action( 'vc_before_init', 'productgrid_integrateWithVC' );

and heres my ajax code :

//AJAX
jQuery(document).ready(function($) {

// We'll pass this variable to the PHP function example_ajax_request

 // use jquery this to get category
$('.cat-trigger').on('click', function(e) {
  e.preventDefault();
var cat = $(this).text();

// This does the ajax request
$.ajax({
    url: nanook_ajax_obj.ajaxurl,
    data: {
        'action':'nanook_ajax_request',
        'cat' : cat
    },
    success:function(data) {
        // This outputs the result of the ajax request
        console.log(data);
    $( ".products" ).empty();
    $('<p>'+cat+'</p>').appendTo('.products');
    },
    error: function(errorThrown){
        console.log(errorThrown);
    }
});
});
});

Any ideas how i can do it please ?

Read more here: Using AJAX to update woocommerce product grid

Leave a Reply

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