NOTE: This article is an INTERNAL article and is not visible to customers, currently. Please only link this article in internal comments, but not public comments.
Issue
- How to develop an asynchronous portlet in DXP?
Environment
- Liferay DXP 7.0+
Resolution
-
In this simple, dummy, reduced scenario, the
view.jsp
of your MVC portlet has this code:<script>
Liferay.on(
'pocEvent',
function() {
console.log("pocEvent listened!");
$.ajax({
url: "https://www.mocky.io/v2/5185415ba171ea3a00704eed",
method: "GET",
error: function() {
console.log("error fetching the data");
},
success: function(data) {
console.log(data);
}
});
}
);
</script> - Your theme (or any other compatible resource, like for example a JS file in the portlet itself) has this code in the
main.js
file:
Liferay.on(
'allPortletsReady',
/*
This function gets loaded when everything, including the portlets, is on
the page.
*/
function() {The theme injects this in the
console.log('all portlet is ready');
Liferay.fire('pocEvent');
}
); - Upon navigating to the page where the portlet is placed, you should see the
{ hello: "world" }
json object printed in the browser's console, along withall portlet is ready
//pocEvent listened!
debug lines - One important note: do not set
"com.liferay.portlet.render-weight=0"
in the portlet's Java class. This will make the portlet behave sequentially, which is a concept opposite to Ajax. According to the DTD:
<render-weight> The default value of render-weight is 1. If set to a value less than 1, the portlet is rendered in parallel. If set to a value of 1 or greater, then the portlet is rendered serially. Portlets with a greater render weight have greater priority and will be rendered before portlets with a lower render weight.
If the ajaxable value is set to false, then render-weight is always set to 1 if it is set to a value less than 1. This means ajaxable can override render-weight if ajaxable is set to false.<ajaxable> The default value of ajaxable is true. If set to false, then this portlet can never be displayed via Ajax.
- The aforementioned portlet and theme are attached here for convenience.