JavaScript Remoting Example
Here’s a basic sample demonstrating how to use JavaScript remoting in your Visualforce pages.
First, create an Apex controller called AccountRemoter:
Other than the @RemoteAction annotation, this looks like any other controller definition.
To make use of this remote method, create a Visualforce page that looks like this:
Notice the following about this markup:
- The JavaScript uses the explicit
invokeActionremoting call, and takes advantage of the$RemoteActionglobal to resolve the correct namespace for the remote action method. - The
event.statusvariable istrueonly if the call was successful. The error handling illustrated by the example is deliberately simple and prints the error message and stack trace from theevent.messageandevent.wherevalues, respectively. You’re encouraged to implement more robust alternative logic for requests where your method call doesn’t succeed. - The
resultvariable represents the object returned from the ApexgetAccountmethod. - Accessing the DOM ID of a plain HTML element is simple, just use the ID of the item.
- DOM IDs of Visualforce components are dynamically generated in order to ensure IDs are unique. The code above uses the technique illustrated in Using $Component to Reference Components from JavaScript to retrieve the component’s ID by accessing it via the
$Componentglobal variable.