Your Page Title
🔍

    Understanding apex:actionFunction Component in Visualforce

    The <apex:actionFunction> component allows you to call Apex controller methods from JavaScript, enabling powerful and dynamic interactions in Visualforce pages. It works like a bridge between client-side scripts and server-side logic.


    Key Features

    • Defines a JavaScript function you can call from anywhere in your page.
    • Invokes Apex methods asynchronously using AJAX.
    • Can update specific areas of the page using rerender.

    Syntax

    xmlCopyEdit<apex:actionFunction name="callServerMethod" action="{!doSomething}" rerender="outputPanel"/>
    

    You can now call callServerMethod() using JavaScript.


    Example: Call Apex Method on Button Click

    xmlCopyEdit<apex:page controller="ActionFunctionController">
        <apex:form>
            <apex:inputText value="{!inputText}" id="inputBox"/>
            <apex:commandButton value="Submit via JS" onclick="callFromJS(); return false;" />
    
            <apex:outputPanel id="outputPanel">
                <p>{!responseText}</p>
            </apex:outputPanel>
    
            <apex:actionFunction name="callFromJS" action="{!processText}" rerender="outputPanel"/>
        </apex:form>
    </apex:page>
    

    Apex Controller:

    apexCopyEditpublic class ActionFunctionController {
        public String inputText { get; set; }
        public String responseText { get; set; }
    
        public void processText() {
            responseText = 'You typed: ' + inputText;
        }
    }
    

    When to Use

    • When you need to call server-side logic from client-side code.
    • If you’re building custom UI interactions using JavaScript.
    • For AJAX calls that require real-time updates.

    Tips

    • Name your function clearly and avoid conflicts with existing JavaScript functions.
    • Always use rerender to control which components get updated.
    • Use immediate="true" if you want to skip validation.