JavaScript Object Notation (JSON) is a text-based way of representing JavaScript object literals, arrays, and scalar data. It is language independent, self-describing, and plain text. It is a good solution for transferring data between systems because it is easy to read, write, and utilize.

CakePHP has built-in functions to serve data as JSON, making it trivial to allow access to data within an application or across the internet.

Define View Classes

In your controller which will be providing the data, implement the viewClasses() method to identify the view you want to support. We'll provide our Users data as JSON, so we need to edit our Controller at /src/Controller/UsersController.php

...
use Cake\View\JsonView;

class UsersController extends AppController
{
  public function viewClasses(): array
  {
    return [JsonView::class];
  }
...

Create Our Data Method

We want to ensure our data is being provided as we intend, and ensure none of the fields we don't want displayed are included, so we will display it in the default layout in a view first before switching to the Ajax layout. Add the data fetch method to our UsersController.

public function fetch($id = null)
{
  $this->Authorization->skipAuthorization();
  // If ajax request, use ajax layout
  if ($this->request->is('ajax')) {
    $this->viewBuilder()->setClassName('Ajax');
  }
  if (empty($id)) {
    $id = $this->request->getQuery('id');
  }
  $data = $this->Users->find()
    ->where(['id' => $id])
    ->select('dob')
    ->first();
  $this->set(compact('data'));
  // Serialize our data
  $this->viewBuilder()->setOption('serialize', ['data']);
}

Add Our Method to Unauthenticated Actions

Since we want to be able to access this data without being logged in, we've added skipAuthorization() to the method, but we also need to add it to addUnauthenticatedActions() in our Users Controller.

public function beforeFilter(\Cake\Event\EventInterface $event)
{
  parent::beforeFilter($event);
  // Configure the login action to not require authentication,
  // preventing the infinite redirect loop issue
  $this->Authentication->addUnauthenticatedActions(['login', 'logout', 'password', 'resetPassword', 'fetch']);
}

Create Our View

A quick way to view our data to verify what is being returned is a simple view. Create /src/templates/Users/fetch.php

<?= $data ?>

Now we can load our data and verify the output is what we were expecting. http://localhost/tutorial/users/fetch/1

We can now use ajax requests for data from our application at http://localhost/tutorial/users/fetch?id=# and it should return a JSON object like the following:

{ "dob": "1999-12-25" }