Thursday 12 March 2015

Requesting AEM Component via AJAX

In AEM pages are created in modular fashion and this modularity is achieved using components. But we often come across a situation where we want a specific component to be reloaded and not the complete page but mostly dispatcher is the main reason for loading a component via AJAX.

As dispatcher caches component's output html due to which dynamicity of a component becomes questionable. For instance if we want a component to show unique results with each request. Loading component via AJAX is one way out for handling such scenarios.

Sample AJAXified component

To request a component via AJAX we will be using a Sling trick. In this trick we will request the URL to the component node then Sling resolution comes into the picture and it look for sling:resourceType property ,executes the script at given path & sends final HTML response.

It is quite straight forward to implement this approach. We need to create a cq:component and the Javascript code for making a AJAX request.  As we would want our component to give unique response each time, we can either use a selector or query parameters and then give response accordingly.

Code snippet below gives an example of how to request the desired component via ajax and show  the latest result.

But for requesting a component's node we need to store the path on which we would be requesting, we will have to store that on our page itself in the page's DOM. Like shown below:

Now we just need to read the path of the component node and request for component to reloaded via AJAX. Here is the sample jQuery method for how to achive this.

I have created a demo component which is loaded on the page via AJAX. To use it one need to drop AJAX Demo Component inside parsys of AJAX Demo Warpper component and on press of reload button it reloads the component via AJAX.

Here is the link for code repository for a sample component that is reloaded via AJAX : Requesting cq:components via AJAX

No comments:

Post a Comment