I'm trying to run a controller action with ajax in a new plugin I'm making. The action needs to return all categories from a group, so nothing impossible here.
When I run the actionUrl in the browser I get the wanted result: an array with the titles of all categories in a group.
But when I call this action while using ajax it results in an empty array.
Ajax call
$.ajax({
url: Craft.getActionUrl('AddEntriesFilter/Index/GetCategories'),
context: document.body,
success: function(response) {
console.log(response);
}
});
Action in controller
public function actionGetCategories()
{
$criteria = craft()->elements->getCriteria(ElementType::Category);
$criteria->group = 'myCategoryHandle';
$cats = $criteria->find();
$regions = array();
foreach ($cats as $cat)
{
$regions[] = $cat->title;
}
$this->returnJson($regions);
}
To test this, I tried to Craft::dd($cats);
and this is already empty.
I also tried to Craft::dd($criteria->count());
and this also gives different results in the ajax call and in the browser. The ajax call returns 0 and the browser returns the wanted result.
After logging the attributes of $criteria I discovered $criteria->find()
is adding a relatedTo attribute. It only does this when running it through Ajax.
Thanks!