Salesforce Menu

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

  1. Javascript Remoting does not use view state, this helps in minimizing the view state related errors for a visualforce page.
  2. 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.
  3. 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{
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">
        Visualforce.remoting.timeout = 120000; 
        function createAccount() {
            var name = document.getElementById('inputId').value;
        function handleResult(result, event) { 
            alert('Account ID : ' + result.Id);
   <input type="text" id="inputId"/>
    <input type="button" onclick="createAccount();" value="Save"/>  

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.

Subscribe Now