I’ve got my snippet called “artists.php” where all Artists are getting listed. I wanted to add a filter by using their Tags. I achieved my goal but i wanted to change my code into AJAX, to accomplish a filtering without reloading the Page. But as i tested it, i saw, that the AJAX response is the whole page?
snippets/artists.php:
<script>
$(document).ready(function() {
// This function checks the radio button based on the filter parameter in the URL
function checkRadioButtonFromURL() {
// Get the current URL
var currentUrl = window.location.href;
// Use URLSearchParams to find the 'filter' parameter
var urlParams = new URLSearchParams(window.location.search);
var filterValue = urlParams.get('filter');
// If there's a filter value, find the radio button with that id and check it
if(filterValue) {
$('#' + filterValue).prop('checked', true);
}
}
// Check the radio button when the page loads
checkRadioButtonFromURL();
$('.category-checkbox').on('change', function() {
var elementId = $(this).attr('id');
//var newUrl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?filter=' + elementId;
var newUrl = `${window.location.href.split('#')}?filter=${elementId}`;
//Redirect to the new URL, causing the page to reload
//window.location.href = newUrl;
$.ajax({
url: newUrl, // The PHP file that will process the filtering
type: 'POST',
data: {param: elementId},
success: function(response) {
console.log(newUrl);
// Replace the content of the artists list with the filtered data
console.log('Gefilterte Daten:', response);
},
error: function(xhr, status, error) {
console.error("Error occurred: " + error);
}
});
});
});
</script>
<ul class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-[1px] pb-5">
<?php
//Debugging the Controller Variables
echo "filterBy: " . ($filterBy) . "</br>";
echo "unfiltered: " . ($unfiltered) . "</br>";
echo "myArtists: " . ($myArtists) . "</br>";
?>
<?php foreach ($myArtists as $artist): ?>
<!-- Artist Output -->
<?php endforeach; ?>
</ul>
snippets/artists.controller.php
<?php
return function () {
$filterBy = get('filter');
$unfiltered = page('artists')
->children()
->listed()
->sortBy('createdon', 'asc');
$myArtists = $unfiltered
->when($filterBy, function ($filterBy){
return $this->filterBy('tags', $filterBy, ',');
});
$filters = $unfiltered->pluck('tags', ',', true);
return [
'test' => 'test',
'filterBy' => $filterBy,
'unfiltered' => $unfiltered,
'myArtists' => $myArtists,
'filters' => $filters,
];
};
Thats my response in the Console with the correct filtered artists (But it’s the whole Page with header and so on…):