martes, 29 de noviembre de 2011

Rendering Paragraphs with AJAX, Part II

In Rendering Paragraphs with AJAX Part 1, I showed a basic example of an AJAX paragraph in Magnolia CMS. We loaded an paragraph via an AJAX call and rendered it on the page.

Now we will see how to send parameters on the AJAX call and display changes by using the model class.

For a use case, suppose you have to display a large amount of content. To make the content easier for the user to browse, you add pagination. You only want to update the paginated content when the user clicks a Previous or Next button.

You need a way to tell the server what page the user is currently on. The server can then provide the previous page or the next page. In order to do this you need a model class, a paragraph definition and a Freemarker template script (.ftl file).

Template script

Add the following code to your Freemarker template script:

<div id="ajax">
[#assign pageIndex = model.pageIndex]
<script>
function next() {
    jQuery.get('${ctx.contextPath}${content.@handle}.html', 
{index: '${pageIndex}'}, 
 function(data) {
         jQuery('#ajax').html(data);
     });  
}
</script>
<div>
   Page: <span id="text">${pageIndex}</span>
</div>
<a href="javascript:next();">NEXT</a>
</div>
The content paragraph to be rendered is inside the div element that has an ID ajax. The script assigns the value that comes from the model method call to a variable pageIndex. In the script, an AJAX call reloads the current paragraph, passing a new parameter index with the value we assigned earlier.

In a nested div element, we write the current value of the variable on the page.

On the last line, we create a NEXT link that the user can click. The click will execute the AJAX call, run the paragraph model, and return the new pageIndex value.

Model class

Now let's see what the model class looks like.
public String execute() {
        
    String index = MgnlContext.getParameter("index");
    if(StringUtils.isNotEmpty(index)) {
        pageIndex = Integer.parseInt(index) +1;
    }
    return super.execute();
}

public int getPageIndex() {
    return pageIndex;
}
The class has two methods:
  • Overridden execute method that reads the parameter we sent by clicking NEXT and adds 1 to pageIndex.
  • getPageIndex method to retrieve the value of the member variable pageIndex.

Paragraph definition



The rendered NEXT  button looks like this on the page.