I'm trying to answer my own question in this post Basically, I have a bunch of checkboxes in multiple categories and when clicked, I want to use Ajax to filter the results and show them on the same screen. I'm building up to that incrementally, and starting out by just trying to get the Ajax to work right with a single category filter.
My Ajax looks like this:
$('#filters input').change(function() {
var value = $(this).val();
$.ajax("ajax.twig?search=" + value, {
type: 'get',
dataType: 'html',
success : function(html) {
$("#ajaxresults").html(html)
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
});
ajax.twig look like this:
{% set searchTerm = craft.request.getParam('search') %}
{% set galleries = craft.entries.section("gallery").colors(searchTerm) %}
{% if galleries|length %}
<div class="gallery">
<ul>
{% for gallery in galleries.all() %}
<li>
<img src="{{ gallery.image[0].url }}" alt="" />
<h2>{{ gallery.title }}</h2>
</li>
{% endfor %}
</ul>
</div>
{% endif %}
If I visit ajax.twig?color=red
manually in the browser, it works as expected and I see the rendered result. However, the page with the filters using ajax just returns the code inside ajax.twig rather than the result of the query. I've also tried using .load() and .get() and had the same result.
Does anyone know what I'm doing wrong? I've been stuck for days. Thanks in advance.