function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Krishna billaKrishna billa 

hi can any one explain when to use ACTION FUNCTION and REMOTE ACTION in detail i much confusion on these both

hi can any one explain when to use ACTION FUNCTION and REMOTE ACTION in detail i much confusion on these both
SFDC_DevloperSFDC_Devloper
Hi,

ACTION FUNCTION:

            ActionFunction is used to execute a method in your Apex Class from within your Visualforce Page asynchronously via AJAX requests. What does asynchronous AJAX requests mean ? This means that Visualforce Pages(otherwise HTML pages when rendered at the Client Side via the Browser) can send data to, and retrieve data from, a server asynchronously (in the background) without interfering with the display and behavior of the existing page. So when we execute an Apex Method via the ActionFunction, the page is not disturbed and the request to the servers(Apex Code compiles and runs on the Salesforce servers while the Visualforce pages which are nothing but HTML pages are rendered by browser at the Client Side) are sent and received in the background. The other way of doing such AJAX requesst to Apex Methods include the Visualforce Remoting. The only difference between the same is that when using the Visualforce Remoting you will have to write some extra lines of JavaScript which is not needed in case of the ActionFunction.

Now, a very simple and a common example of ActionFunction is mimicking the Field Dependency feature on Visualforce Pages. Say for example you had two Picklists – Select the Object and Select the Field. When a user selects an Object, the next Picklist automatically gets populated with the Fields that belong to the object.

Well, I will not be using this one since that might get a bit complicated with couple of Describe calls but let us consider an another one. For example say you had two Picklists like this- Select the Alphabet(from which you can select from choices like –A, B, C and D) and then a Select the Fruit(from which you can select the fruit of your choice). So when a User selects A, all the Fruits starting with A gets populated in the 2nd picklist and when the User selects B, all the Fruits starting with B gets populated and so on.

Controller:
public class Controller{
    public List<SelectOption> Alphabets {get; set;}
    public List<SelectOption> Fruits {get; set;}
   
    public String SelectedAlphabet {get; set;}
   
    /*A Constructor which will build the intial list of Alphabets*/
    public Controller(){
        Alphabets = new List<SelectOption>();
        Fruits    = new List<SelectOption>();
       
         /*This is to add the NONE option for our Picklists*/
        SelectOption option = new SelectOption('--None--', '--None--');
        Alphabets.add(option);
        Fruits.add(option);
       
        option = new SelectOption('A', 'A');
        Alphabets.add(option);
       
        option = new SelectOption('B', 'B');
        Alphabets.add(option);       
    }
   
    /*This Method that will actually build the Fruits list for us. The ActionFunction will be calling this function as and when a User changes an Alphabet from the 1st List.*/
    public void createFruitList(){
        /*Always clear the List when begin so that previous values will be removed.*/
        Fruits.clear();
       
        Fruits.add(new SelectOption('--None--', 'None'));
       
        if(SelectedAlphabet == 'A'){
            Fruits.add(new SelectOption('Apple','Apple'));
            Fruits.add(new SelectOption('Apricot','Apricot'));
        }
        else if(SelectedAlphabet == 'B'){
            Fruits.add(new SelectOption('Banana','Banana'));
            Fruits.add(new SelectOption('Blackberry','Blackberry'));
        }
    }
}

VisualForce Page:
<apex:page controller="Controller">
    <apex:form>
        <apex:actionFunction action="{!createFruitList}" name="generateFruits" reRender="selFruits" />
        <br/>
        Select the Alphabet:
        <apex:selectList id="selAlphabets" value="{!SelectedAlphabet}" size="1" onchange="generateFruits()">
            <apex:selectOptions value="{!Alphabets}">
            </apex:selectOptions>
        </apex:selectList>
        <br/> 
        Select the Fruit:
        <apex:selectList id="selFruits" size="1">
            <apex:selectOptions value="{!Fruits}">
            </apex:selectOptions>
        </apex:selectList>           
    </apex:form>
</apex:page>



REMOTE ACTION:

@RemoteAction in Visual force page
JavaScript remoting in Visualforce provides support for some methods in Apex controllers to be called via JavaScript.

JavaScript remoting has three parts:
  • The remote method invocation you add to the Visualforce page, written in JavaScript.
  • The remote method definition in your Apex controller class. This method definition is written in Apex, but there are few differences from normal action methods.
  • The response handler callback function you add to or include in your Visualforce page, written in JavaScript.
To use JavaScript remoting in a Visualforce page, add the request as a JavaScript invocation with the following form:

    [namespace.]controller.method(
       [parameters...,]
       callbackFunction,
       [configuration]);
  • namespace is the namespace of the controller class. This is required if your organization has a namespace defined, or if the class comes from an installed package.
  • controller is the name of your Apex controller.
  • method is the name of the Apex method you’re calling.
  • parameters is the comma-separated list of parameters that your method takes.
  • callbackFunction is the name of the JavaScript function that will handle the response from the controller. You can also declare an anonymous function inline. callbackFunction receives the status of the method call and the result as parameters.
  • configuration configures the handling of the remote call and response. Use this to specify whether or not to escape the Apex method’s response. The default value is {escape: true}.
VisualForce Page:
<apex:page controller="sample">
    <script type="text/javascript">
    function getAccountJS() 
    {
        var accountNameJS = document.getElementById('accName').value;        
        sample.getAccount( accountNameJS, 
        function(result, event)
        {
            if (event.status) 
            {
                // demonstrates how to get ID for HTML and Visualforce tags
                document.getElementById("{!$Component.theBlock.thePageBlockSection.theFirstItem.accId}").innerHTML = result.Id;
                document.getElementById("{!$Component.theBlock.thePageBlockSection.theSecondItem.accNam}").innerHTML = result.Name;
            } 
            else if (event.type === 'exception') 
            {
                document.getElementById("errors-js").innerHTML = event.message;
            } else 
            {
                document.getElementById("errors-js").innerHTML = event.message;
            }
        }, {escape:true});
    }
    </script>
    Account Name :<input id="accName" type="text" />
    <button onclick="getAccountJS()">Get Account</button>
    <div id="errors-js"> </div>
    <apex:pageBlock id="theBlock">
        <apex:pageBlockSection id="thePageBlockSection" columns="2">
            <apex:pageBlockSectionItem id="theFirstItem">
                <apex:outputText id="accId"/>
            </apex:pageBlockSectionItem>
            <apex:pageBlockSectionItem id="theSecondItem" >
                <apex:outputText id="accNam" />
            </apex:pageBlockSectionItem>
        </apex:pageBlockSection>
    </apex:pageBlock>
</apex:page>
Controller:
global class sample 
{
    public String accountName { get; set; }
    public static Account account { get; set; }
    public sample() { }
    
    @RemoteAction
    global static Account getAccount(String accountName) 
    {
        account = [select id, name, phone, type, numberofemployees from Account where name = :accountName ];
        return account;
    }
}



Thanks,
Rockzz
Krishna billaKrishna billa
thank u rcoks but i have still doubt at what situtiation i have to go remote action 
SFDC_DevloperSFDC_Devloper
Hi Krishna,

 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.

  here small example:

Controller:

@RemoteAction
global static Account getAccount(string accountname) { .//Some logic.. }
Your VF / Javascript:

<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>

[And remember, if it helps, mark it as "Best Answer", if not ... reply ]


Thanks,
Rockzz


Krishna billaKrishna billa
thanks again rockzzz! and i have still a doubt ,why to call a controller method from java script ,we have action attribute to call a method then what is need to call a method from java script ,please explain in detail 

Sasank VaranasiSasank Varanasi
Action function will bring in view state while getting data into visual force. Remoteaction will not add viewstate to visual force page. That is because you yourself are maintaining the state of variables that you are using inside that method. Remoteaction is particularly helpful while coding very large pages and rendering large amount of data from controller. For example, when you are using nested repeat or pageblocktable viewstate increases considerably. Chances are you will hit 135 Kb limit very soon. To avoid that remoteaction is one of the solutions
Poornachandrarao P 3Poornachandrarao P 3
Thanks Sasank !!
atul patil 7atul patil 7
Hi Krishna,
1.Action Function doesn't return anything  but by using remote action you can get return value from controller to visualforce page. so if there is any requrement that you have  to process something on the basis of result then use RemoteAction 
2. Remoteaction will not add viewstate to visual force page. so while handling large amount of data use RemoteAction

Thanx,
Atul Patil
Salesforce Developer
www.zen4orce.com