Modern websites frequently rely on AJAX (Asynchronous JavaScript and XML) to deliver dynamic, responsive user experiences without reloading the entire page. In TYPO3, we can harness the power of AJAX by setting up a dedicated typeNum endpoint in TypoScript and handling asynchronous calls with an Extbase controller. This blog post will walk you through each step—from configuring TypoScript for AJAX to returning JSON responses and consuming them in your frontend JavaScript.
Why Use AJAX in TYPO3?
1. Improved User Experience: No need to reload the entire page—just update specific components.
2. Better Performance: Fetch only necessary data, reducing server load and page load times.
3. Modular and Maintainable: Keep your logic organized by isolating AJAX calls in a dedicated controller/action.
1. Create an AJAX Endpoint with TypoScript
The first step is to create a special PAGE object in TypoScript and assign a unique typeNum to handle your AJAX requests.
ajax_page = PAGE
ajax_page {
typeNum = 123456 # Unique number for the AJAX call
config {
disableAllHeaderCode = 1
additionalHeaders = Content-type:application/json
xhtml_cleaning = 0
admPanel = 0
debug = 0
no_cache = 1
}
10 = USER
10 {
userFunc = TYPO3\CMS\Extbase\Core\Bootstrap->run
extensionName = YourExtension
pluginName = YourPlugin
vendorName = YourVendor
controller = YourController
action = yourAjaxAction
}
}
Key Points
1. typeNum: Assign a unique integer to distinguish this AJAX request from other TYPO3 page types.
2. disableAllHeaderCode: Ensures no extra HTML headers are included—ideal for JSON responses.
3. USER: Routes the request to your Extbase controller/action, which will process the request and return data.
2. Implement the Extbase Controller
Next, create (or update) an Extbase controller action specifically for handling the AJAX request. By leveraging the JsonView, TYPO3 can automatically return a JSON response, making it easy to consume in your JavaScript.
namespace Vendor\YourExtension\Controller;
use TYPO3\CMS\Extbase\Mvc\Controller\ActionController;
use TYPO3\CMS\Extbase\Mvc\View\JsonView;
class YourController extends ActionController
{
protected $defaultViewObjectName = JsonView::class; // Return JSON response
public function yourAjaxAction()
{
// Your business logic here
$data = [
'message' => 'Hello, this is a response from the AJAX call',
'status' => true,
];
// Assign data to the view for JSON output
$this->view->assign('value', $data);
}
}
Key Points
1. JsonView: Automatically converts the assigned PHP array/object into JSON output.
2. Business Logic: Perform any server-side operations here—e.g., database queries, validations, or custom business rules.
3. Trigger the AJAX Request from JavaScript
Finally, you need a way to call the newly created AJAX endpoint from your frontend. Below is an example of using plain JavaScript (XMLHttpRequest); however, you can also use fetch() or jQuery’s $.ajax() if preferred.
// Create an XMLHttpRequest object
var xhr = new XMLHttpRequest();
// Define the URL (with the typeNum parameter)
var url = "/?type=123456"; // Replace '123456' with your actual typeNum
// Open the request
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
// On successful response
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 300) {
// Parse JSON response
var response = JSON.parse(xhr.responseText);
console.log(response); // Handle the server response data
} else {
console.error('Request failed. Status: ' + xhr.status);
}
};
// On request error
xhr.onerror = function() {
console.error('AJAX request failed');
};
// Data to send
var data = "param1=value1¶m2=value2";
// Send the request
xhr.send(data);
Key Points
1. xhr.open("POST", url, true): Set the HTTP method (GET or POST), target URL, and asynchronous flag.
2. xhr.setRequestHeader(): (Optional) Use this to set content types or custom headers.
3. Response Handling: JSON responses can be parsed with JSON.parse() for easy access.
4. (Optional) Configure Clean URLs with Routing
For TYPO3 v9 and above, you can make your AJAX endpoint more user-friendly by setting up route enhancers. In your config.yaml, define a route for your typeNum:
routeEnhancers:
AjaxType:
type: Simple
defaultController: 'Vendor\YourExtension\Controller\YourController::yourAjaxAction'
requirements:
type: '\d+'
default: ''
This lets you craft pretty URLs instead of using /?type=123456. Adjust your JavaScript request accordingly.
Real-World Example
A typical scenario might involve listing records from an extension such as one our TYPO3 extension Helpdesk use:
listAction = PAGE
listAction {
typeNum = 741852
config {
disableAllHeaderCode = 1
additionalHeaders = Content-type:application/json
xhtml_cleaning = 0
admPanel = 0
}
10 = USER
10 < styles.content.get
10 {
userFunc = TYPO3\CMS\Extbase\Core\Bootstrap->run
extensionName = NsHelpdesk
pluginName = Helpdesk
vendorName = NITSAN
controller = Tickets
switchableControllerActions {
Tickets {
1 = list
}
}
# Carry plugin settings along in the AJAX call
stdWrap.trim = 1
select {
where = list_type = "nshelpdesk_helpdesk"
}
renderObj < tt_content.list.20.nshelpdesk_helpdesk
}
}
By referencing /?type=741852 (or your fancy route if configured), you can asynchronously fetch a list of support tickets from Helpdesk and handle them in your JavaScript code.
Conclusion
Implementing AJAX in TYPO3 using TypoScript’s typeNum and Extbase is straightforward and powerful. By separating your AJAX logic into a dedicated controller action, you keep the system clean, modular, and easy to maintain. Whether you’re updating small components or building a full-fledged single-page application, TYPO3’s flexibility accommodates it all.
Got questions or unique use cases? Drop them in the comments or reach out to the T3Planet community. We’d love to hear how you’re using AJAX in your TYPO3 projects!
Happy AJAX-ing with TYPO3!
Post a Comment