In Cakephp I’m trying to make jquery ajax as json request, but Cakephp always response with missing template as error below:
{
"message": "Template file \/Commissions\/json\/history.ctp\u0022 is missing.",
"url": "commissions\/get-users?%7B%22company_id%22:%22e615a47c-a210-4a13-b3a7-edaa71f%22%7D\u0026amp;_=1679045364774",
"code": 500,
"file": "Tele\/TeleCommissions\/json\/history.ctp",
"line": 1583
}
and here is my code. Any help appreciate.
public function getUsers()
{
if ($this->request->is('ajax')) {
$this->autoRender = false;
$this->response = $this->response->withDisabledCache();
$this->loadModel('Users');
$users = $this->Users->find('list', [
'keyField' => 'id',
'valueField' => 'username'
])
->where([
'Users.is_active' => 1,
'Users.is_deleted' => 0,
'Users.type' => MARKETING,
'Users.company_id' => $this->request->getQuery('company_id')
]);
return $this->response->withType('application/json')
->withStringBody(json_encode([
'status' => 1,
'data' => $users,
]));
}
}
$('body').on('change', '#company-id', function (e) {
e.preventDefault();
let companyId = $(this).val();
console.log(companyId);
$.ajax({
type: 'GET',
url: '<?= $this->Url->build(['controller' => 'Commissions', 'action' => 'getUsers']) ?>',
data: JSON.stringify({ company_id: companyId }),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
cache: false,
beforeSend: function (xhr) {
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
}
}).done(function(data) {
if (data) {
let option = '<option value="">Select Users</option>';
$.each(data.data, function(index, value) {
option += '<option value="' + index + '">' + value + '</option>';
});
$('.user-id').empty().html(option);
<?php if ($this->request->getQuery('user_id')): ?>
$('.user-id').val('<?= $this->request->getQuery('user_id') ?>');
<?php endif; ?>
}
});
});