Skip to content

08. AJAX

ihofmann edited this page Nov 30, 2014 · 1 revision

Using AJAX

Every page or block can be also loaded via AJAX without any special configuration. AJAX means, roughly, that only a part of the current web page is getting refreshed, without reloading the whole page. This reduces the data traffic and loading times. And it looks cool.

The system supports AJAX actions with only a couple of commands.

Processing a form with AJAX

Forms which do not lead to a new page can be processed with an AJAX request.

Let's take our Hello page with form that we have created earlier. Everything that we need to do in order to process the form without reloading the whole page, is to alter the button a little bit:

<button type="submit" 
	class="btn btn-primary ajaxSubmit"
	data-ajaxtarget="pagecontent">{{ i18n.getMessage('button_save') }}</button>

You only have to add the CSS class "ajaxSubmit" and attribute "data-ajaxtarget". The AJAX target must be a valid ID within the final HTML document. This is the ID of the element that will be refreshed. You can get the ID when analyzing the HTML code with your web browser.

As you can see, the form validation will be still executed and also the success message will be shown. Additionally, the form elements get disabled as long as the loading is in progress.

By the way: The form will be still processed even when the user has disabled JavaScript in his settings.

Refresh contents by clicking on a link

Not only forms, but also hyper links can trigger AJAX requests. The principle is the same, but the link usually requires some additional request parameters which would be normally passed in a form. In the above example, we could integrate a link as follows:

<a href="#mylink" class="ajaxLink" 
	data-ajaxtarget="pagecontent"
	data-ajaxquerystr="page=hello&action=sayhello&myname=test&myage=20">Test</a>

This link will update the page content and display a success message.

Refresh a block on page load

Blocks can be loaded via AJAX without the need of any user action. This is how you can load a block automatically once the main page has been loaded:

<div class="ajaxLoadedBlock" id="myDivElement" 
			data-ajaxblock="myBlockId">
</div>

Important is that the DIV element has an ID. This can be any unique ID within the document.

Refresh block automatically

A block that has been loaded on page load can be refreshed every X seconds. Example for every 10 seconds:

<div class="ajaxLoadedBlock" id="myDivElement" 
			data-ajaxblock="myBlockId"
			data-refreshperiod="10">
</div>

Refresh alerts only on demand

If you do not want that the loading of an AJAX block immediately clears all visible application alerts (such as error or success messages), you can specify this with the HTML attribute ignoreemptymessages.

Example:

<div class="ajaxLoadedBlock" id="myDivElement" 
		data-ajaxblock="myBlockId" data-ignoreemptymessages="true">
</div>