Total Pageviews

Monday, August 15, 2016

Liferay: Client Side IPC via Events/Ajax

Client Side IPC using Ajax is another way of achieving communicating between portlets from client size. This mechanism was introduced in JSR-286 (Portlet 2.0) specification and provides a very lightweight and decoupled mechanism to communicate portlets purely in the browser through a JavaScript events mechanism.

The API of this system is very simple and is based on two methods
Liferay.fire(eventName, data);
Liferay.on(eventName, function, [scope]);
Prerequisite for this includes - setting <requires-namespaced-parameters> to false, in liferay-portlet.xml file of the both the portlets, which makes allows to share data via Ajax call and adding both the portlets in the same page after deployment.

Let’s see some snippets:

Portlet 1: JS code for setting params

$(document).on('ready',function(){
 var param1 = "I'm a sample value of Param 1";
 var param2 = "I'm a sample value of Param 2";
 $.ajax({
  url:'',
  dataType: "json",
  data:{param1: param1, param2: param2},
  type: "get",
  success: function(data){
   Liferay.fire('setParamsViaAjax', {eventData: data});
   },
  complete: function(){
   alert('Success');
   },
  error: function(){
   alert(Some 'Error');
   }
 });
});


Portlet 2: JS code for fetching the Params
Liferay.on('setParamsViaAjax', function(event) {
 alert("Param 1: " + event.eventData.param1);
 alert("Param 2: " + event.eventData.param2);
}); 


That’s all for today. Thanks for reading and have a nice day.