Activity Forums Salesforce® Discussions Define Javascript Remoting for Salesforce Apex Controllers. Reply To: Define Javascript Remoting for Salesforce Apex Controllers.

  • Anurag

    September 19, 2018 at 2:01 pm

    Hi Prachi,

    Here’s a basic sample demonstrating how to use JavaScript remoting in your Visualforce pages

    First, create an Apex controller called AccountRemoter:

    global with sharing class AccountRemoter {

    public String accountName { get; set; }
    public static Account account { get; set; }
    public AccountRemoter() { } // empty constructor

    global static Account getAccount(String accountName) {
    account = [SELECT Id, Name, Phone, Type, NumberOfEmployees
    FROM Account WHERE Name = :accountName];
    return account;

    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:

    <apex:page controller="AccountRemoter">
    <script type="text/javascript">
    function getRemoteAccount() {
    var accountName = document.getElementById('acctSearch').value;

    function(result, event){
    if (event.status) {
    // Get DOM IDs for HTML and Visualforce elements like this
    document.getElementById('remoteAcctId').innerHTML = result.Id
    ).innerHTML = result.NumberOfEmployees;
    } else if (event.type === 'exception') {
    document.getElementById("responseErrors").innerHTML =
    event.message + "<br/>\n<pre>" + event.where + "</pre>";
    } else {
    document.getElementById("responseErrors").innerHTML = event.message;
    {escape: true}

    <input id="acctSearch" type="text"/>
    <button onclick="getRemoteAccount()">Get Account</button>
    <div id="responseErrors"></div>

    <apex:pageBlock id="block">
    <apex:pageBlockSection id="blockSection" columns="2">
    <apex:pageBlockSectionItem id="firstItem">
    <span id="remoteAcctId"/>
    <apex:pageBlockSectionItem id="secondItem">
    <apex:outputText id="acctNumEmployees"/>