0

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);
    }
});
  • Does [this part of the manual](https://book.cakephp.org/4/en/views/json-and-xml-views.html) help? Maybe [this question](https://stackoverflow.com/questions/42378793/how-to-output-custom-http-body-contents-with-cakephp-3-4-echoing-causes-unable/42379581#42379581)? Or [this one](https://stackoverflow.com/questions/41042107/cakephp3-how-can-i-return-json-data/51859677)? – Greg Schmidt Nov 07 '21 at 15:15
  • Yes thanks you and sorry. I will post my solution later. – thedoomer1000 Nov 07 '21 at 16:02

1 Answers1

0

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

aknd
  • 749
  • 2
  • 6
  • 24