Loading Extbase data with fetch()
A page does not have to contain all of its data when it leaves the server. A script in the browser can request data later, with the Fetch API, and update part of the page without reloading it. This technique is commonly called AJAX, although the data is usually JSON today.
An Extbase action can answer such a request. This page builds a small example from end to end: an action that returns JSON, a URL for it, and a script that displays the result.
On this page
Showing live data in a cached Extbase list
The conference list of the example site is cached, as a list should be. Each conference also shows how many seats are left, and that number changes with every registration. Rendering it into the cached list would show outdated numbers. Making the whole list non-cacheable would render it on every request for the sake of one number per conference.
The list therefore stays cached, and a script loads the numbers separately. Four pieces work together: a plugin with an action that returns the numbers as JSON, a page type that delivers them at their own URL, the list template that tells the script where to find them, and the script itself.
An Extbase action that returns JSON for a script
The plugin is only configured, not registered as a content element: no editor places it on a page, the page type renders it. Its action is listed as non-cacheable, so the numbers are current on every request:
<?php
use MyVendor\MyExtension\Controller\ConferenceSeatsController;
use TYPO3\CMS\Extbase\Utility\ExtensionUtility;
defined('TYPO3') or die();
ExtensionUtility::configurePlugin(
'MyExtension',
'ConferenceSeats',
[ConferenceSeatsController::class => ['seats']],
[ConferenceSeatsController::class => ['seats']],
);
The action collects the numbers and renders them with JsonView:
<?php
declare(strict_types=1);
namespace MyVendor\MyExtension\Controller;
use MyVendor\MyExtension\Domain\Repository\ConferenceRepository;
use Psr\Http\Message\ResponseInterface;
use TYPO3\CMS\Extbase\Mvc\Controller\ActionController;
use TYPO3\CMS\Extbase\Mvc\View\JsonView;
class ConferenceSeatsController extends ActionController
{
public function __construct(
protected readonly ConferenceRepository $conferenceRepository,
) {}
protected function initializeSeatsAction(): void
{
$this->defaultViewObjectName = JsonView::class;
}
public function seatsAction(): ResponseInterface
{
$seats = [];
foreach ($this->conferenceRepository->findUpcoming() as $conference) {
$seats[] = [
'uid' => $conference->getUid(),
'seatsLeft' => $conference->getSeatsLeft(),
];
}
$this->view->assign('seats', $seats);
$this->view->setVariablesToRender(['seats']);
return $this->jsonResponse();
}
}
find stands for the repository method the list uses, and
get for a model method that computes the free seats. The
action builds a small array per conference with exactly the two values the
script needs, and renders a single variable, so the response is a bare JSON
array:
[
{"uid": 12, "seatsLeft": 4},
{"uid": 15, "seatsLeft": 0}
]
Giving the Extbase JSON action its own URL with a page type
A plugin on a regular page cannot deliver the JSON on its own, see Delivering the JSON of an Extbase action at its own URL. A typeNum page type that renders only the plugin gives it a URL:
conferenceSeats = PAGE
conferenceSeats {
typeNum = 1762214402
config {
disableAllHeaderCode = 1
admPanel = 0
}
10 = EXTBASEPLUGIN
10 {
extensionName = MyExtension
pluginName = ConferenceSeats
}
}
plugin.tx_myextension_conferenceseats {
persistence.storagePid = 42
}
The page type renders the plugin directly, without a content element, so the
plugin takes its storage folder from TypoScript, see
Rendering the plugin without a content element. The response carries the content
type application/ that
json set, so the
PAGE
object needs no header configuration.
A PageType decorator
can map the page type to a suffix such as seats., as the
feed example does. The script
does not depend on it, because it receives the URL from the page.
Passing the URL of the Extbase JSON action to a script
The list template writes the URL into a data- attribute, so the script does
not have to build it.
f: with a
page links the
current page in its current language, with the page type of the seats plugin.
Each conference carries its uid, and an empty, hidden placeholder for the
number:
<f:asset.script
identifier="conferenceSeats"
src="EXT:my_extension/Resources/Public/JavaScript/conference-seats.js"
defer="1"
/>
<ul data-seats-url="{f:uri.page(pageType: 1762214402)}">
<f:for each="{conferences}" as="conference">
<li data-conference="{conference.uid}">
<f:link.action action="show" arguments="{conference: conference}">
{conference.title}
</f:link.action>
<span data-seats hidden>
Seats left: <span data-seats-count></span>
</span>
</li>
</f:for>
</ul>
The f:asset.script ViewHelper adds the script to the page once, however often the template is rendered.
The URL is the same for every visitor, so it is part of the cached list. Only the response behind it changes.
Fetching and displaying Extbase JSON data with JavaScript
The script requests the URL, reads the JSON, and fills in the number for every conference it finds in the list:
async function showSeatsLeft(list) {
const response = await fetch(list.dataset.seatsUrl);
if (!response.ok) {
return;
}
const seats = await response.json();
for (const conference of seats) {
const element = list.querySelector(
`[data-conference="${conference.uid}"] [data-seats]`,
);
if (element) {
element.querySelector('[data-seats-count]').textContent =
conference.seatsLeft;
element.hidden = false;
}
}
}
const list = document.querySelector('[data-seats-url]');
if (list) {
showSeatsLeft(list);
}
fetchsends a() GETrequest to the URL from the data- attribute and returns a promise for the response.response.is true for a status code between 200 and 299. Any other status leaves the placeholders hidden.ok response.parses the body into JavaScript values, here the array the action returned.json () - The script shows a placeholder only after it has filled in the number.
Requests from
fetch to the same site send the visitor's cookies by
default, so the action sees the same frontend user as the page, and the page
type applies the same access restrictions as the page.
The list works without the script as well. If the script does not run or the request fails, the visitor sees the list without the numbers, which is what progressive enhancement means.
Caching the JSON response of an Extbase action
Because the action is non-cacheable, the plugin is rendered as a USER_INT object. TYPO3 caches the page type with a placeholder and runs the action on every request. The content type of the action still reaches every response, including those whose page comes from the cache.
Every request still runs the frontend: TYPO3 resolves the site and the page, checks access, and loads the TypoScript, mostly from caches. For one request per page view that is acceptable. A script that polls every few seconds, or many scripts on one page, multiply that cost. For such requests, a middleware endpoint answers without running the frontend.
Data that changes rarely does not need a non-cacheable action. Leave the action cacheable, and the page type delivers the JSON from the page cache like any other page. Use cache tags to clear it when the data changes.
Answering a script with an error status from an Extbase action
The status code of the action's response reaches the browser when it is 300 or higher. An action that has to report an error, for example because a requested record does not exist, returns a response with such a status:
return $this->jsonResponse(json_encode(
['error' => 'Conference not found'],
JSON_THROW_ON_ERROR,
))->withStatus(404);
Status codes below 300, such as 201 Created or 204 No Content, do not
reach the browser: TYPO3 answers with 200 OK.
An error status also makes the plugin non-cacheable for that request, so an error is never stored in the page cache.
Next steps after loading Extbase data with fetch()
The action in this example used JsonView to render its data, which explains in more detail which variables end up in the JSON and how to shape it. Ways to deliver non-HTML output from TYPO3 compares the page type used here with the other options, such as answering in a middleware before any page is rendered.