I want to fetch data from the database and send it with Ajax in CakePhp4 from the controller to the view.
I've implemented it (rarely found documentations) but it doesnt return me the array. It wants a whole view, but I dont want to create a whole page, just return the array.
Error:
The view for CountriesController::getAll() was not found.
In my src/controller/CountriesController.php
public function getAll() {
$results = $this->Countries->find('all', [
'contain' => ['PLZ']
]);
$this->set(compact('results'));
$this->set('_serialize', 'results');
}
In my template/countries/index.php
$.ajax({
type: 'get',
url: 'countries/getAll',
beforeSend: function(xhr) {
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
},
success: function(response) {
if (response.error) {
alert(response.error);
console.log(response.error);
}
if (response.content) {
$('#target').html(response.content);
}
},
error: function(e) {
alert("An error occurred: " e.responseText.message);
console.log(e);
}
});
CodePudding user response:
try something like this:
config/routes.php
$routes->prefix('Api', function (RouteBuilder $routes) {
$routes->setExtensions(['json']);
$routes->fallbacks(DashedRoute::class);
});
Controller/Api/CountriesController.php
public function getall()
{
$countries = $this->Countries->find('all', [
'contain' => ['PLZ']
]);
$data = [
'countries' => $countries,
];
$this->set(compact('data'));
$this->viewBuilder()->setOption('serialize', ['data']);
}
see if this works first: /api/countries/getall.json