When calling an AJAX Method in a Module Helper file the method has to be static. I have no app context there, when doing the following:
public static function getDataAjax()
{
$data = ExampleHelper::getJArticles();
return $data;
}
public static function getJArticles(){
$app = Joomla\CMS\Factory::getApplication();
$model = $app->bootComponent('com_content')->getMVCFactory()->createModel('Articles', 'Site', ['ignore_request' => true]);
$articles = $model->getItems();
return $articles;
}
An error 500 got thrown:
Call to a member function get() on null
#0 /Users/MyUser/Sites/joomla5.site/libraries/src/MVC/Model/ListModel.php(222): Joomla\Component\Content\Site\Model\ArticlesModel->getListQuery()
#1/Users/MyUser/Sites/joomla5.site/libraries/src/MVC/Model/ListModel.php(271): Joomla\CMS\MVC\Model\ListModel->_getListQuery()
#2 /Users/MyUser/Sites/joomla5.site/components/com_content/src/Model/ArticlesModel.php(651)...
There is a similar question here (about getting articles in the backend) (Link) but as far as i can see the solution there does not help me.
I would like to use the model rather then doing my own database query here...
Edit: The AJAX call is done via com_ajax:
...
async loadData() {
let requestString = this.prepareRequest();
const res = await fetch(requestString);
if (res.ok) {
let parsed = await res.json();
if (parsed.data && parsed.data.length > 0) {
this.data = parsed.data;
}
}
return this.data;
}
prepareRequest() {
if (!this.checkConfiguration()) return;
let requestString = 'index.php?option=com_ajax&module=' + this.moduleName + '&method=' + this.method + '&format=json';
if (this.backendModule) {
requestString = 'administrator/' + requestString;
}
requestString += '&limit=' + this.limit + '&page=' + this.page;
return requestString;
}
checkConfiguration() {
return !!(this.moduleName && this.method);
}
...
params
state on the model. You can see the code in the linked question. I think my answer applies here too.