Wednesday, 23 July 2014

How to create a Remote Call?

Visualforce remote javascripting  is a powerfull feature of force.com. It has an advantage over the actionfunction or similar ajax components which is perfomance. It is superfast and light weight, higly customisable. Here I will explain how to create remote method and call using a javascript.


Create a static controller method with @remoteaction annotation.

         public static string testRemoteCall(String input){

The method can be either public or gobal not private. Always the method has to be static. Return type can be any apex Type. @Remoteaction will make the method avaliable to a VF page through javascript object. which I will discuss later.

Here is the complete controller code.

public class testRemote{   
 
 public testRemote(){
 }

@remoteAction
public static string testRemoteCall(String input){
  return 'Hello'
}
 
public class wrapper{
  public string name;
  public integer id;
}
}

In the visualforce page the class should be added is either controller or extensions. Now you can call the controller method using a javascript.  For the above controller method  testRemoteCall there is one parameter so the remote call will have total  two parameter the latest being a callback function. Below is the javascript to call the testRemoteCall method.

 testRemote.testRemoteCall(textBoxValue ,function(result,event){ 
 //do some stuff
});
   
the second argument  is a function which is callback to hold the result of the call.  the result object will hold the return value from the controller method. Event is an object which holds the status and other parameters.
Inside the callback function you can update DOM elements.

Below is the complete code for controller and Vf.

public class testRemote{
 
 public testRemote(){
 }

@remoteAction
public static string testRemoteCall(String input){
  return  'Hello';
}
 
public class wrapper{
  public string name;
  public integer id;
}
}


<apex:page controller="testRemote">
 <input type="textbox" id="textbox"/>
 <button type="button" onclick="callRemote()" >Click</button>
 <div id="output"></div>
 <script>
function callRemote(){
 var textBoxValue = document.getElementById('textbox').value;
 testRemote.testRemoteCall(textBoxValue ,function(result,event){ 
console.log(event);
document.getElementById('output').innerHTML =  result;
 },{escape:false});
}
 </script>
</apex:page> 

No comments:

Post a Comment