Activity Forums Salesforce® Discussions How to add Javascript Remoting to a Visualforce Page in Salesforce?

  • madhulika shah

    Member
    September 18, 2018 at 1:30 pm

    Hi,

    To add javascript remoting to a vfpage, here is an example:

    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

    @RemoteAction
    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;

    Visualforce.remoting.Manager.invokeAction(
    '{!$RemoteAction.AccountRemoter.getAccount}',
    accountName,
    function(result, event){
    if (event.status) {
    // Get DOM IDs for HTML and Visualforce elements like this
    document.getElementById('remoteAcctId').innerHTML = result.Id
    document.getElementById(
    "{!$Component.block.blockSection.secondItem.acctNumEmployees}"
    ).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}
    );
    }
    </script>

    <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>
    <apex:pageBlockSectionItem id="secondItem">
    <apex:outputText id="acctNumEmployees"/>
    </apex:pageBlockSectionItem>
    </apex:pageBlockSection>
    </apex:pageBlock>
    </apex:page>

    Hope this helps.

  • Avnish Yadav

    Member
    September 18, 2018 at 1:30 pm

    Hello,

    Remote action function in salesforce allows user to access any method from any class through javasrcipt methods, and get the result as a javascript object for further manipulation.

    Points to remember while implementing remote action function:

    Remote action method should have @RemoteAction annotation.
    The method should also be Global and Static

    Example:-

    global with sharing class ContactJs {
    public ContactJs() { } // empty constructor

    @RemoteAction //the function to be called in remote action should use this annotation
    global static list<Contact> getcon() {
    //function should be static and global else it will throw error
    list<Contact> con1 = [SELECT id,name FROM contact limit 5];
    if(con1!=null && !con1.isEmpty()){
    return con1;
    }else{
    return  new list<contact>();
    }
    }
    }
    Vf Page:-

    <apex:page controller="ContactJs">
    <script type = "text/javascript">
    function getRemoteContact() {
    var a;
    Visualforce.remoting.Manager.invokeAction(
    //Invoking controller action getcon
    '{!$RemoteAction.ContactJs.getcon}',

    function(result, event){
    //We can access the records through the parameter result
    //event.status determines if there is error or not
    if(event.status){
    document.getElementById('remoteContactId').innerHTML = 'Contact Name: <br/><br/>';
    for(a=0;a<result.length;a++){
    document.getElementById('remoteContactId').innerHTML +=  result[a].Name +'<br/>';
    }
    }
    },
    {escape: true}
    );
    }
    </script>

    <button onclick="getRemoteContact()">Get Contact</button>
    <div id="responseErrors"></div>
    <apex:pageBlock id="block">
    <apex:pageBlockSection id="blockSection" columns="2">
    <span id="remoteContactId"></span>
    </apex:pageBlockSection>
    </apex:pageBlock>
    </apex:page>

    Hope this, will help you.

    Thanks.

  • Parul

    Member
    September 18, 2018 at 1:36 pm

    Hi

    JavaScript code can be written in a Visualforce page and can be included in a Visualforce page by using a static resource within the script.

    Example: Code snippet

    <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) {
    // Code for callback handling
    }
    }, {escape: true}
    );
    }
    </script>

     

    Controller:

    @RemoteAction
    global static String getItemId(String objectName) { … }

     

    Thanks

  • shariq

    Member
    September 18, 2018 at 3:07 pm

    Hi,

    JavaScript remoting is a tool that front-end developers can use to make an AJAX request from a Visualforce page directly to an Apex controller. JavaScript remoting allows you to run asynchronous actions by decoupling the page from the controller and to perform tasks on the page without having to reload the entire page.
    In addition, JavaScript remoting can help alleviate view state issues while still executing in the context of the user viewing the page. JavaScript remoting is the most efficient way of calling the controller and passing data in from the page, because you can ensure that you’re passing only the data that you need each time that you make a call.

    Thanks

  • shariq

    Member
    September 20, 2018 at 11:44 pm

    Hi,

    Adding code -

    global with sharing class AccountRemoter {

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

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

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

    Visualforce.remoting.Manager.invokeAction(
    '{!$RemoteAction.AccountRemoter.getAccount}',
    accountName,
    function(result, event){
    if (event.status) {
    // Get DOM IDs for HTML and Visualforce elements like this
    document.getElementById('remoteAcctId').innerHTML = result.Id
    document.getElementById(
    "{!$Component.block.blockSection.secondItem.acctNumEmployees}"
    ).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}
    );
    }
    </script>

    <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>
    <apex:pageBlockSectionItem id="secondItem">
    <apex:outputText id="acctNumEmployees"/>
    </apex:pageBlockSectionItem>
    </apex:pageBlockSection>
    </apex:pageBlock>
    </apex:page>

    Hope this helps.

  • Parul

    Member
    September 21, 2018 at 4:07 am

    Notice the following about this markup:

    The JavaScript uses the explicit invokeAction remoting call, and takes advantage of the $RemoteAction global to resolve the correct namespace for the remote action method.
    The event.status variable is true only if the call was successful. The error handling illustrated by the example is deliberately simple and prints the error message and stack trace from the event.message and event.where values, respectively. You’re encouraged to implement more robust alternative logic for requests where your method call doesn’t succeed.
    The result variable represents the object returned from the Apex getAccount method.
    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 $Component global variable.

     

    Thanks

Log In to reply.

Popular Salesforce Blogs