Welcome to this short tutorial about Extbase and Ajax. If you are familiar with TYPO3 you might have heard of the eID concept that gives you the possibility to stop the rendering process very early and run your own script instead. That means, only the most needed components are initiated to save memory and time and at the earliest moment possible you output whatever you need. That indeed is a nice feature of TYPO3 but I’m not gonna talk about it this time for different reasons.
Instead I want to introduce another way having the ability to use all the features TYPO3 and Extbase come with. So, let’s get started with a very small new extension. Btw: I recommend you to check out my example extension on github for a better understanding of what I am talking about now.
So, what has to be done. At first you need a working Extbase extension with just one controller, two actions and one template for one of these actions. To keep it simple there is no model, no repository, nothing but the controller.
class Tx_AsAjaxexample_Controller_ExampleController extends Tx_Extbase_MVC_Controller_ActionController {
/**
* @return void
*/
public function indexAction() {
}
/**
* @return void
*/
public function ajaxAction() {
$json = array(
'jQuery',
'ExtJS',
'Prototype',
'MooTools'
);
return json_encode($json);
}
}
The index action does nothing else but render the template. The ajaxAction is a bit special as I do not use the render function but return a json encoded static array (line 20). This is done because the rendering of Fluid uses htmlspecialchars and destroys the JSON string. Now there is another problem. Calling the ajaxAction in the frontend you get valid JSON but also the HTML-structure of your standard template wrapped around it. To avoid that, typoscript comes into play. Let’s have a look at it:
ajaxPage = PAGE
ajaxPage {
typeNum = 99
config {
disableAllHeaderCode = 1
additionalHeaders = Content-type:application/json
xhtml_cleaning = 0
admPanel = 0
}
10 < tt_content.list.20.asajaxexample_pi1
}
All the magic here is to create a new PAGE object with a typeNum different from “0″ (line 2) and assign the content of the extension to the blank page (line 11). Adding type=99 to the request url let’s this PAGE come into play and outputs nothing else but what we need, the JSON string. Please be sure not to print the parsetime ( <!-- Parsetime: 254ms --> ) by adding the following line to your localconf.php:
$TYPO3_CONF_VARS["FE"]["debug"] = '0';
Now we’re ready to put the plugin on a site and view it in the frontend. In case you are not using my example extension here’s the template for you:
<button id="ajax">fetch list</button>
<button id="clear">delete list(s)</button>
<div id="list">List(s):</div>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
<script type="text/javascript">
ajaxUrl = "{f:uri.action(action:'ajax', pageType:'99')}";
(function($) {
$(document).ready(function(){
$('#clear').click(function(){
$('#list').text('List(s):');
return false;
});
$('#ajax').click(function(){
$.getJSON(ajaxUrl, function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' key '">' val '</li>');
});
$('<ul/>', {
html: items.join('')
}).appendTo('#list');
});
return false;
});
});
})(jQuery);
</script>
Update: Added return false; to the click-functions for disabling their normal submit-behaviour.
I guess the code is self-explaining. There’s one button to do the request, one to clear the DOM and a placeholder div for the result. The rest is easy JS with jQuery. Having my extension installed you can now test it. As you probably can see it’s not super-fast but also not too bad. I did some tests with firebug and the request mostly took about 300ms.
Alright, that’s it again. Hopefully that is a little help in your daily business.
Useful Links:
Something you didn’t understand? Leave a reply.
Servus Alexander,
versuche gerade für meine Extbase/Fluid extension Ajax einzubauen. Hab deine extension as_ajaxexample installiert und die Ausgabe durch das Plugin funktioniert, jedoch der Ajax request nicht. Habe das gleiche Problem mit extjs_mvc_examples.
Hast du irgend eine Idee woran das liegen könnte?
Viele Grüße
Daniel
Hey Daniel,
war bis heute in Urlaub, daher erst jetzt die Antwort.
Also ohne da irgend etwas zu sehen, kann ich nur spekulieren und das bringt sicherlich nichts. Wär super, wenn du den Problemfall online hast und ich da mal per Link zugreifen könnte. Ist das möglich?
Hallo, sehr schöne Einführung ohne irritierendes Beiwerk. Funktionierte auf Anhieb (außer in meinem Template, das ein Formular enthielt, da löst der Button offenbar was falsches aus?).
Werde mal Komplexeres testen – vielen Dank!
Hey Stefan,
es kann sein, dass der Button einen Submit des Formulars auslöst. Habe den JavaScript-Teil angepasst und um ein return false; erweitert, dass die normale Funktion der Buttons unterdrückt.