Javascript Remoting In Visualforce
Javascript Remoting is a way to call apex methods directly from your javascript in your visualforce pages. This is an alternative to calling apex methods with an action function or action support.
Advantages of Javascript Remoting
- Javascript Remoting does not use view state, this helps in minimizing the view state related errors for a visualforce page.
- Javascript Remoting can be used to pass any parameter to your apex method directly, no need to use apex params like in the action function.
- Javascript remoting is asynchronous, but it can be used pretty effectively with callback methods.
@RemoteAction Annotation
If we want to call an apex method from javascript, we need to define it with the @RemoteAction annotation. The method also must be static for this to work.
Example, to create an Account record we can define a remote action method like this,
public class PageController{ @RemoteAction public static Account createAccount(String name ) { Account acc = new Account(Name = name); insert acc; return acc; } }
Calling Method from Javascript
If we want to call the above method from a visualforce page, we first need to set the above class as the controller for my visualforce page.
Then, we can use the below code in the <script> tag in the visualforce page to call the remote action method.
<apex:page controller="PageController" sidebar="false" showHeader="false"> <script> Visualforce.remoting.timeout = 120000; function createAccount() { var name = document.getElementById('inputId').value; console.log(name); Visualforce.remoting.Manager.invokeAction( '{!$RemoteAction.PageController.createAccount}', name, handleResult ); } function handleResult(result, event) { alert('Success'); alert('Account ID : ' + result.Id); } </script> <input type="text" id="inputId"/> <input type="button" onclick="createAccount();" value="Save"/> </apex:page>
Output :
When we click the Save button. The account is saved to the database.
If we navigate to this record id, we can see the Account record.
When the apex method finishes processing, the callback function (handleResult) is called. We can do post-processing in this callback method. We can also pass multiple parameters in the remoting invocation in a comma-separated way.