What I'm trying to achieve is to enable users to filter posts based on the selection of the checkboxes located on the sidebar.
I've created a custom post type called projects and a couple of taxonomies such as clients and expertises. I found this which is exactly what I want to my page to look like with AJAX. However, I think there are some missing code in there. Anyway, I have managed to display all of taxonomies out with checkboxes without any problems.
<!-- Show clients taxonomies in a checkbox -->
<?php foreach( $myClient as $a ) { ?>
<div id="cat_id">
<input class="client_filter" name="<?php echo $a->term_id; ?>" type="checkbox"><?php echo " ".$a->cat_name; ?>
</div>
<?php } ?>
<!-- show expertises taxonomies in a checkbox -->
<?php foreach( $expertStyles as $b ) { ?>
<div>
<input class="expertise_filter" name="<?php echo $b->term_id; ?>" type="checkbox"><?php echo " ".$b->cat_name; ?>
</div>
<?php } ?>
In my script.js
, I have the code below:
jQuery(document).ready(function($) {
/* This function will be called on click event */
var optionsChecked = function() {
/* initialize all the variables */
jQuery('.filter-result-form').html("");
var clients = [];
var expertises = [];
var term_id = jQuery('#cat_id').text();
/* loop and push any checked checkboxes into empty array */
jQuery(".client_filter input:checked").each(function() {
var client_id = jQuery(this).attr('name');
clients.push(client_id);
});
jQuery(".expertise_filter input:checked").each(function() {
var expertise_id = jQuery(this).attr('name');
expertises.push(expertise_id);
});
/* collect all the data */
var myData = {
'filter':1,
'term_id': term_id,
'client': clients,
'expertise': expertises
}
/* Ajax url */
var url = "/mysite/ajax";
jQuery.post( url, myData, function( myData ){
jQuery('.filter-result-form').append( myData );
});
}
$( "input[type='checkbox']" ).on("click", optionsChecked);
});
When I run this code, I see nothing come up in the filter result form. I must admit that I'm still learning about jQuery and AJAX.