Use JavaScript remoting in Visualforce to call methods in Apex controllers from JavaScript. Create pages with complex, dynamic behavior that isn’t possible with the standard Visualforce AJAX components.
[namespace.]controller.method(
[parameters...,]
callbackFunction,
[configuration]
);The remote method call executes synchronously, but it doesn’t wait for the response to return. When the response returns, the callback function handles it asynchronously. See Handling the Remote Response for details.
{ buffer: true, escape: true, timeout: 30000 }| Name | Data Type | Description |
|---|---|---|
| buffer | Boolean | Whether to group requests executed close to each other in time
into a single request. The default is true. JavaScript remoting optimizes requests that are executed close to each other in time and groups the calls into a single request. This buffering improve the efficiency of the overall request-and-response cycle, but sometimes it’s useful to ensure all requests execute independently. |
| escape | Boolean | Whether to escape the Apex method’s response. The default is true. |
| timeout | Integer | The timeout for the request, in milliseconds. The default is 30000 (30 seconds). The maximum is 120000 (120 seconds, or 2 minutes). |
<script type="text/javascript"> Visualforce.remoting.timeout = 120000; // Set timeout at page level
function getRemoteAccount() { var accountName = document.getElementById('acctSearch').value; // This remoting call will use the page's timeout value Visualforce.remoting.Manager.invokeAction( '{!$RemoteAction.AccountRemoter.getAccount}', accountName, handleResult ); } function handleResult(result, event) { ... } </script>
Override a page-level timeout configuration on a per-request basis by setting the timeout in the configuration object for that request, as described above.
JavaScript remoting requests can use OAuth 2.0 for authentication, instead of requiring a standard username and password login process. OAuth allows cross-application and cross-org integrations that aren’t possible to do securely with standard authentication.
A Visualforce page that uses OAuth for authentication configures it at the page level, and uses OAuth for all JavaScript remoting requests. Other than configuration, using JavaScript remoting is exactly the same.
<script type="text/javascript"> Visualforce.remoting.oauthAccessToken = <access_token>; // ... </script>
oauthAccessToken is an OAuth authentication token obtained by your page’s code. Obtaining and updating an access token is straightforward OAuth, with one addition. JavaScript remoting OAuth authentication requests the “visualforce” scope, so your token must be generated with this or a scope that contains it, including “web” or “full”. Set scope=visualforce (or “web” or “full”) in your OAuth request.
For information about obtaining access tokens, and using OAuth with the Force.com platform, see Authenticating Remote Access Applications in the Salesforce online help and wiki.developerforce.com/page/Digging_Deeper_into_OAuth_2.0_on_Force.com.
Visualforce.remoting.Manager.invokeAction(
'fully_qualified_remote_action',
invocation_parameters
);The fully qualified remote action is a string that represents the complete path to the remote action method, including namespace, base class, and so on: namespace[.BaseClass][.ContainingClass].ConcreteClass.Method. Use $RemoteAction in an expression to automatically resolve the namespace, for example {!$RemoteAction.MyController.getAccount}.
<script type="text/javascript"> function getRemoteAccount() { var accountName = document.getElementById('acctSearch').value; Visualforce.remoting.Manager.invokeAction( '{!$RemoteAction.MyController.getAccount}', accountName, function(result, event){ if (event.status) { document.getElementById('acctId').innerHTML = result.Id document.getElementById('acctName').innerHTML = result.Name; } else if (event.type === 'exception') { document.getElementById("responseErrors").innerHTML = event.message; } else { document.getElementById("responseErrors").innerHTML = event.message; } }, {escape: true} ); } </script>
@RemoteAction global static String getItemId(String objectName) { ... }
Your method can take Apex primitives, collections, typed and generic sObjects, and user-defined Apex classes and interfaces as arguments. Generic sObjects must have an ID or sobjectType value to identify actual type. Interface parameters must have an apexType to identify actual type.
Your method can return Apex primitives, sObjects, collections, user-defined Apex classes and enums, SaveResult, UpsertResult, DeleteResult, SelectOption, or PageReference.
| @RemoteAction Scope | Visualforce Page | Non-Global Component | Global Component | iframe |
|---|---|---|---|---|
| Global Remote Method | Allowed | Allowed | Allowed | Allowed |
| Public Remote Method | Allowed | Allowed | Error | Error |
| Top Level Container | ||||
|---|---|---|---|---|
| @RemoteAction Accessed From | Visualforce Page | Non-Global Component | Global Component | iframe |
| Global Component | Allowed | Allowed | Allowed | Allowed |
| Non-Global Component | Allowed | Allowed | Allowed only if non-global component doesn't include public remote methods. | Allowed only if non-global component doesn't include public remote methods. |
| <apex:include><apex:composition> | Allowed within the same namespace; error if namespaces are different, and the included page or its child hierarchy contains public remote methods. | n/a | n/a | Error |
When a @RemoteAction method is looked up or called, Visualforce inspects the page controller’s inheritance hierarchy and finds @RemoteAction methods in the controller’s ancestor classes.
global with sharing class ChildRemoteController extends ParentRemoteController { } global virtual with sharing class ParentRemoteController extends GrandparentRemoteController { } global virtual with sharing class GrandparentRemoteController { @RemoteAction global static String sayHello(String helloTo) { return 'Hello ' + helloTo + ' from the Grandparent.'; } }
<apex:page controller="ChildRemoteController" > <script type="text/javascript"> function sayHello(helloTo) { ChildRemoteController.sayHello(helloTo, function(result, event){ if(event.status) { document.getElementById("result").innerHTML = result; } }); } </script> <button onclick="sayHello('Jude');">Say Hello</button><br/> <div id="result">[Results]</div> </apex:page>
You can declare @RemoteAction methods with interface parameters and return types, instead of being restricted to concrete classes. This, for example, allows a package provider to package a remote method and associated interface, which subscriber organizations can call from Visualforce pages, passing in their own class that implements the packaged interface.
public class RemoteController { public interface MyInterface { String getMyString(); } public class MyClass implements MyInterface { private String myString; public String getMyString() { return myString; } public void setMyString(String s) { myString = s; } } @RemoteAction public static MyInterface setMessage(MyInterface i) { MyClass myC = new MyClass(); myC.setMyString('MyClassified says "' + i.getMyString() + '".'); return myC; } }
Visualforce.remoting.Manager.invokeAction(
'{!$RemoteAction.RemoteController.setMessage}',
{'apexType':'thenamespace.RemoteController.MyClass', 'myString':'Lumos!'},
handleResult
);The response to a remote method call is handled asynchronously by the callback function provided in the remote method call. Your callback function will receive as parameters an event object representing the status of the remote call, and the result object returned by the remote Apex method. Your function can update information and user interface elements on the page based on the data returned.
Apex primitive data types returned by result—such as strings or numbers—are converted to their JavaScript equivalents. Apex objects that are returned are converted to JavaScript objects, while collections are converted to a JavaScript array. Keep in mind that JavaScript is case-sensitive, so id, Id, and ID are considered different fields.
As part of a JavaScript remote call, if the Apex method response contains references to the same object, the object won't be duplicated in the returned JavaScript object, and instead, the rendered JavaScript object will contain references to the same object. An example is an Apex method which returns a list that contains the same object twice.
By default, the response of the remote call must return within 30 seconds, after which the call will time out. If your request needs longer to complete, configure a longer timeout, up to 120 seconds.
The response of the remote call has a maximum size of 15 MB.
<script type="text/javascript"> function getRemoteAccount() { var accountName = document.getElementById('acctSearch').value; Visualforce.remoting.Manager.invokeAction( '{!$RemoteAction.MyController.getAccount}', accountName, function(result, event){ if (event.status) { document.getElementById('acctId').innerHTML = result.Id document.getElementById('acctName').innerHTML = result.Name; } else if (event.type === 'exception') { document.getElementById("responseErrors").innerHTML = event.message + "<br/>\n<pre>" + event.where + "</pre>"; } else { document.getElementById("responseErrors").innerHTML = event.message; } } ); } </script>
In general, <apex:actionFunction> is easier to use and requires less code, while JavaScript remoting offers more flexibility.