jueves, 27 de octubre de 2011

Rendering Paragraphs with AJAX, Part I

Ever wondered how to reload just some paragraphs on your page? Imagine you have pagination and you want to reload just the paginated paragraph when clicking previous/next? Is Magnolia CMS capable of this without complex coding? Yes, and on this post you will find some ways of achieving this.

First thing to know is, since Magnolia CMS version 4.x paragraphs are autorenderable. What does this mean? It means you can copy the path of a paragraph, paste it in the address bar of your browser and you will see the paragraph rendered. Try the following URL from our demo site, it will render the teaser of the Article page.

What can you do with this? It means you don't need to create a servlet or anything to render a paragraph dynamically on a page. Just a call to the appropriate script will let you load any paragraph on our page.

Here is a sample using JQuery. Add this code into a .ftl file. You also need to create a paragraph definition and add it to be used in a template.
<script type="text/javascript">
function loadArticleTeaser() {
  jQuery.get('${contextPath}/demo-project/main/00.html',function(data) {
<div id="ajax"> </div>
<a href="javascript:loadArticleTeaser()">Load Teaser via AJAX call </a>
The JQuery call (http://api.jquery.com/jQuery.get/) will get the specified URL and, on success, will run the method that loads the result (paragraph) from the AJAX call into a div with ID "ajax". To run the whole thing you just need to click the "Load Teaser via AJAX call" link.

This is a basic sample of an AJAX paragraph. In the next post you will see how to send parameters and process them in the paragraph model class.