sgalinski / sg-ajax
sgalinski Ajax Handler - Handles our ajax implementation.
Requires
- typo3/cms-core: ^13.4.0
- typo3/cms-extbase: ^13.4.0
- typo3/cms-fluid: ^13.4.0
- typo3/cms-frontend: ^13.4.0
Replaces
- sgalinski/sg_ajax: 6.0.3
This package is not auto-updated.
Last update: 2025-07-24 11:29:51 UTC
README
License: GNU GPL, Version 2
Repository: https://gitlab.sgalinski.de/typo3/sg_ajax
Please report bugs here: https://gitlab.sgalinski.de/typo3/sg_ajax
About
Offers an easy-to-use API for implementing AJAX requests within your TYPO3 Extensions.
The examples in this readme use jQuery, but this extension can be used with any other JavaScript library that offers an AJAX api.
Usage
Generally, you need an Ajax Controller to receive the request and register it with sg_ajax.
Depending on your use case, the following tasks are necessary:
Frontend Ajax registration
- Ensure to add a map entry to the route enhancers! Note that you might need to adapt it to your own needs.
routeEnhancers:
PageTypeSuffix:
type: PageType
default: /
index: ''
map:
sgajax.html: 1595576051
Call the AjaxRegistration::configureAjaxFrontendPlugin function in the ext_localconf.php of your extension
\SGalinski\SgAjax\Service\AjaxRegistration::configureAjaxFrontendPlugin('my_extension_key', [ // must be located in the directory "EXT:XXX/Classes/Controller/Ajax" \Vendor\ExtensionName\Controller\Ajax\AjaxController::class => 'myActionOne, myActionTwo', ] );
Add a controller in Classes/Controller/Ajax with the chosen name and extend it with this class:
\SGalinski\SgAjax\Controller\Ajax\AbstractAjaxController
Example Controller from EXT:sg_account:
<?php
namespace SGalinski\SgAccount\Controller\Ajax;
use Exception;
use Psr\Http\Message\ResponseInterface;
use SGalinski\SgAccount\Service\GravatarService;
use SGalinski\SgAccount\Service\PasswordService;
use SGalinski\SgAjax\Controller\Ajax\AbstractAjaxController;
/**
* Ajax Controller
*/
class AccountAjaxController extends AbstractAjaxController {
/**
* Generates a gravatar image uri based on the user's email address
*
* @param string $email
* @return ResponseInterface
*/
public function getGravatarImageAction($email): ResponseInterface {
return $this->jsonResponse(json_encode(GravatarService::createGravatarUri($email)));
}
/**
* Generates a new password based on the password format configuration
*
* @return ResponseInterface
*/
public function generatePasswordAction(): ResponseInterface {
return $this->htmlResponse(PasswordService::generatePassword());
}
}
Endpoint for Javascript usage
You should always use the ViewHelpers provided to generate the Ajax Urls. You can do so by creating the Ajax link and reading it in JavaScript.
Place the link in a Fluid Template:
{namespace sgajax=SGalinski\SgAjax\ViewHelpers} <sgajax:link.ajax class="ajaxlink" style="display: none;" extensionName="ProjectThemeMegamenu" controller="Ajax\AjaxController" action="myActionOne"></sgajax:link.ajax> <!-- OR something like this: uri.ajax and access the URL in your JavaScript --> <button data-ajax-url="{sgajax:uri.ajax(extensionName: 'SgAccount', controller: 'Ajax\AccountAjax', action: 'getGravatarImage', parameters: linkVars)}" data-email="{user.email}">
There is also an uri.ajax viewhelper to only return the URI if you want to add it to a data attribute. It might be more convenient in many situations.
You can add parameters in the form:
`
tx_sgajax[parameters][query]`
.Example: JavaScript usage (the uri.ajax-VH result is used here):
export default class ProfilePicture { /** * Initializes the ProfilePicture instance. * * @param {HTMLElement} root The upload event. */ constructor(root) { this.initGravatarCollector(); } /** * Initializes the gravatar image collector. */ initGravatarCollector() { const gravatarBtn = this.dom.root.querySelector('[data-crop = "gravatar"]'); gravatarBtn.addEventListener('click', async (event) => { event.preventDefault(); if (this.state.loading) { return; } const result = await this.makeGravatarRequest(gravatarBtn); /** * result has format like * "https:\/\/www.gravatar.com\/avatar\/21232f297a57a5a743894a0e4a801fc3?d=mm&s=250&r=g" * (with quotes) * RegEx /"|\\/g matches all " or \ globally. */ this.gravatarOnloadHandler(result.replace(/["\\]/g, ''), gravatarBtn); }); } /** * Makes the request to the gravatar API. * * @param {HTMLElement} button The button that is clicked to get the gravatar image. * @returns {Promise<string>} The URL to the gravatar image. */ async makeGravatarRequest(button) { button.classList.add('loading'); this.state.loading = true; const url = button.dataset.ajaxUrl; const email = ProfilePicture.getGravatarEmail(button); // setting the ajax parameters const data = { // eslint-disable-next-line camelcase tx_sgajax: { parameters: { email } } }; const result = await window.fetch(url, { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}, body: data }); return result.json(); // or result.text() } }
Basic Example with jQuery (the link.ajax-VH result is used here):
$.post( $('.ajaxlink').attr('href'), { tx_sgajax: { parameters: { one: parameter } } } );
Developer Guide
Controller Classes
Ajax/AbstractAjaxController
This class extends TYPO3\CMS\Extbase\Mvc\Controller\ActionController and should be used instead if your controller needs to be able to process AJAX requests.
function processRequest
Extends the parent function by providing exception handling specific to AJAX calls.
function returnData
Gives the option to return JSON instead of a Fluid view.
Ajax/FrontendDispatcher
This is the main entrypoint of the sgajax functionality. It provides a middleware that handles the request if tx_sgajax is given as a parameter. This is done by injecting the parameters into a TypoScript PAGE configuration that takes over the Extbase bootstrap process and proceeds with the request as it would have been called directly this way.
Service Classes
AjaxRegistration
Provides two static functions to register or configure your AJAX plugins.
function registerAjaxFrontendPlugin
This needs to be called in your ext_tables.php to register your frontend plugin.
function configureAjaxFrontendPlugin
This needs to be called in your ext_localconf.php to configure your frontend plugin.
ViewHelper
Link/AjaxViewHelper
This ViewHelper renders the ajax link for the frontend. You need to give it the extensionName, controller and action to be able to generate the link.
Uri/AjaxViewHelper
This ViewHelper renders the ajax url for the frontend. You need to give it the extensionName, controller and action to be able to generate the link.