Mitkees & Webcenter

Into the charm of Oracle Webcenter and ADF

Tag Archives: server

Call a bean method after ajax call


Many requirements asks to call external service using ajax or do some javascript like using js calendars and on user click send the response to the bean to save it in database or to do some business validation.

The way to do that is using serverListener & clientListener .

The serverListener tag is a declarative way to register a server-side listener that should be executed when a custom client event is fired.

while The clientListener tag is a declarative way to register a client-side listener script to be executed when a specific event type is fired.

I have created a small demo application that calls ajax call & jquery to get location & ip and then we will send it to back bean which will be printed in the console.

Lets see the steps

1.create a jspx page and add a button like this

 <af:panelGroupLayout id="pgl1" layout="vertical">
<af:commandButton text="Get My Location" id="cb1">
<af:clientListener type="action" method="callAjaxAndNotifyServer"/>
<af:serverListener type="servListener"
method="#{backingBeanScope.DemoBB.getAjaxCallbackValue}"/>
</af:commandButton>
</af:panelGroupLayout>

2. add af:resource with the code below

 var actionbtn;
 var response_Json
 function callAjaxAndNotifyServer(actionEvent) {
 actionEvent.cancel();
 actionbtn = actionEvent.getSource();//
 alert(actionbtn);
 $.ajax( {
 url : "http://ip-api.com/json/", data : '', type : "GET", error : function (XMLHttpRequest, textStatus, errorThrown) {

 alert('error');
 ajaxError(XMLHttpRequest, textStatus, errorThrown);
 },
 success : function (data) {

 response_Json = JSON.stringify(data);

 console.log(response_Json);
 AdfCustomEvent.queue(actionEvent.getSource(), "servListener",
 {
 fvalue : response_Json
 },true);
 return false;
 },
 error : function (xhr, status, err) {

 console.log('error');
 var err = eval("(" + xhr.responseText + ")");
 alert('' + err.Message);
 console.log('Error in Ajax
 call:' + err.Message);
 }
 });
 }

where
actionEvent.cancel(); is needed if you are using commandbutton without partialsubmit=”true”
and
AdfCustomEvent.queue(actionEvent.getSource(), “servListener”,
{
fvalue : response_Json
},true);
return false;
registers the custom event and set parameter “fvalue” with the json string value

3.create a bean for example backbean demoBB with method name getAjaxCallbackValue 

that you already referenced in your serverListner in step 1 & add the code to this method as follows to print the value

public void getAjaxCallbackValue(ClientEvent clientEvent) {
System.out.println("-----------------------------------------");
System.out.println(clientEvent.getParameters().get("fvalue"));
System.out.println("-----------------------------------------");
}

 

 


			
%d bloggers like this: