So I’m calling on the following AJAX function in order to pull and display specific categorical posts whenever a corresponding button is pushed:
<script>
// Brochure AJAX
function term_ajax_get(termID) {
jQuery("#loading-animation").show();
var ajaxurl = 'http://localhost/kskj-portal/wp-admin/admin-ajax.php';
jQuery.ajax({
type: 'POST',
url: ajaxurl,
data: {"action": "load-filter2", term: termID },
success: function(response) {
jQuery(".brochure-post-container").append(response);
jQuery("#loading-animation").hide();
return false;
}
});
}
</script>
The function is being called upon using the onclick attribute within the HTML in order to update the function’s input (termID) dynamically:
<?php foreach ($products as $product):
// setup the product/cateogory ID
$product_name = $product->name;
$product_id= $product->term_id;
$product_slug = $product->slug;
?>
<div class="product-container OFF" onclick="term_ajax_get(<?php echo $product->term_id; ?>)">
Is there a way where I can toggle the specific post being displayed? Basically if a button is pushed, its corresponding posts are displayed. If the button is pushed again, the posts are hidden. If one button is pushed, and then another button is pushed, both categories posts display at the same time until one of the buttons is pressed again.
Right now every time a button is being pushed it appends that category’s post onto the page. I need to get the category onto the page when pushed, but I don’t know how to remove it when its corresponding button is pushed again, or how to add other categories when both buttons are selected.
There are quite a few solutions. In the example below, you could just use
data
attribute of the element, and depending on your needs, load fresh data via ajax each time, or switch visibility of already existing elements (to prevent connections).Put each ajax response into an unique element (in the example below, each element has its unique
data-term-id
attribute), so that you can easily check presence of an element later on.PHP:
Js script: