Actionfunction Component with Example Featured Image

If you’ve been learning Salesforce development for any amount of time, you’ve probably run into a scenario where you want to call an Apex method from JavaScript — without refreshing the entire page. That’s exactly where the action function component with example becomes your best friend.

The <apex:actionFunction> component is one of Salesforce’s most powerful Visualforce tools. It bridges the gap between client-side JavaScript logic and server-side Apex controller methods using AJAX requests. For beginners and intermediate developers alike, understanding this component unlocks a whole new level of dynamic, responsive page behavior.

In this post, we’ll break down what <apex:actionFunction> is, how it works, what its key attributes do, and walk through a real-world example so you can apply it right away.

What Is the apex:actionFunction Component?

At its core, the <apex:actionFunction> component provides support for invoking controller action methods directly from JavaScript code using an AJAX request.

In plain English: it lets you define a JavaScript function name in your Visualforce page, and when that function is called anywhere in your JavaScript, it triggers an Apex method on the server — asynchronously, without a full page reload.

This is especially useful when you want parts of your UI to update dynamically based on user interactions like clicking a button, changing a dropdown, or checking a checkbox.

How Is It Different from apex:actionSupport?

A common point of confusion for beginners is the difference between <apex:actionFunction> and <apex:actionSupport>. Here’s the key distinction:

Unlike <apex:actionSupport>, which only provides support for invoking controller action methods from other Visualforce components, <apex:actionFunction> defines a new JavaScript function which can then be called from within a block of JavaScript code.

Think of it this way:

  • <apex:actionSupport> attaches AJAX behavior directly to a specific Visualforce component (like an input field or a panel). The event lives on the component itself.
  • <apex:actionFunction> creates a standalone JavaScript function you can call from anywhere in your JavaScript — from onclick handlers, custom scripts, or even chained function calls.

This flexibility is what makes <apex:actionFunction> so powerful in real-world Salesforce development.

Key Attributes of the Action Function Component

Before diving into an example, let’s understand the attributes that make this component work. Knowing them well will save you hours of debugging later.

Actionfunction component with example

Required Attributes

name — This is the name of the JavaScript function that gets generated. When you write name="myFunction", Salesforce creates a JavaScript function called myFunction() that you can invoke anywhere in the page.

action — This maps to the Apex controller method you want to call. Written using Visualforce expression syntax: action="{!myControllerMethod}". Note that this attribute is optional — if you leave it out, the page simply refreshes.

Important Optional Attributes

reRender — One of the most-used attributes. As soon as the action method completes, the components specified by the reRender attribute are refreshed. You pass the id of any component you want to update without reloading the full page.

immediate — A Boolean value that specifies whether the action associated with the component should happen immediately or not. If set to true, the action happens immediately and Validation rules are skipped automatically. If there is no value defined, it defaults to false.

oncomplete — Specifies a JavaScript function to run after the AJAX response is processed. Great for chaining actions or showing confirmation messages.

status — Links to an <apex:actionStatus> component to show a loading spinner or message during the AJAX call. This massively improves user experience.

timeout — Sets a time limit (in milliseconds) for the AJAX request. Good for preventing long-running requests from hanging the UI.

Important Rule: The <apex:actionFunction> component must always be a child of an <apex:form> component. Placing it outside the form tag will cause it to break silently.

Action Function Component with Example: Step-by-Step

Let’s build a practical example. We’ll create a Visualforce page that multiplies a number by two every time a user clicks a link — without reloading the page. This is the classic “actionFunction” demo and it perfectly illustrates how all the pieces connect.

Step 1: Create the Apex Controller

public class ActionFunctionDemo {
    
    public Integer value { get; set; }
    
    public ActionFunctionDemo() {
        value = 1;
    }
    
    public PageReference timesTwo() {
        value = value * 2;
        ApexPages.addMessage(
            new ApexPages.Message(ApexPages.Severity.INFO, 'Result: ' + value)
        );
        return null;
    }
}

Here’s what this controller does:

  • It declares a public value property and initializes it to 1 in the constructor.
  • The timesTwo() method doubles the current value and adds a page message showing the result.
  • It returns null so the page doesn’t navigate away after the action.

Step 2: Create the Visualforce Page

<apex:page controller="ActionFunctionDemo">

    <apex:outputPanel id="result">
        <apex:pageMessages />
        <p>Current Value: <b>{!value}</b></p>
        <a onclick="squarefunction('{!value}'); return false;">
            Click to Double the Value
        </a>
    </apex:outputPanel>

    <apex:form>
        <apex:actionFunction 
            name="squarefunction" 
            action="{!timesTwo}" 
            reRender="result">
                <apex:param name="arg1" value="" assignTo="{!value}" />
        </apex:actionFunction>
    </apex:form>

</apex:page>

What's Happening Here?

Let’s trace through the logic:

  1. The page renders with value = 1.
  2. The user clicks the “Click to Double the Value” link, which fires the onclick JavaScript event.
  3. The onclick handler calls squarefunction('{!value}') — which is the JavaScript function created by <apex:actionFunction>.
  4. This triggers an AJAX call to the timesTwo() Apex method on the server.
  5. The Apex method doubles the value and adds a page message.
  6. The reRender="result" attribute tells Visualforce to refresh only the <apex:outputPanel id="result"> section — not the whole page.
  7. The user sees the updated value instantly: 2, then 4, then 8, then 16, and so on.

The Role of apex:param

Notice the <apex:param> inside the actionFunction. The <apex:param> component is used to define arguments on the function. The param component must be used inside the actionFunction component.

This allows you to pass values from the Visualforce page to your controller method dynamically — which is incredibly useful when working with dynamic data like row IDs in a table.

Passing Parameters from JavaScript to Apex

One of the more advanced (and extremely useful) patterns with <apex:actionFunction> is passing parameters from JavaScript into the Apex controller. When you call this action tag, you are free to add multiple parameters between Apex and Visualforce methods. Apex class is the solution here that helps to initialize variables outside the method since parameters cannot be passed from Visualforce page directly.

Here’s the practical pattern:

<apex:actionFunction name="updateRecord" action="{!processUpdate}" reRender="outputSection">
    <apex:param name="recordId" value="" assignTo="{!selectedId}" />
</apex:actionFunction>

<!-- Calling it from JavaScript -->
<script>
    function handleRowClick(id) {
        updateRecord(id);
    }
</script>

In this pattern, selectedId is a property in your controller. When updateRecord(id) is called from JavaScript, the id value gets assigned to selectedId in the controller before processUpdate() runs. This is the foundation for building interactive data tables and record-level operations in Visualforce.

Real-World Use Cases

The action function component with example scenarios spans a wide range of real Salesforce customizations:

Dynamic Field Rendering — Show or hide fields based on picklist selection without a full page refresh. For example, when a customer priority picklist changes, a JavaScript method is called, and the corresponding controller action method specified in the actionFunction component checks if the priority is “High” and sets a boolean variable — causing a phone text box to render automatically without refreshing the full page.

Progress Indicators — Combine oncomplete and status attributes to build multi-step operations with loading animations and progress bars.

Inline Record Operations — Trigger create, update, or delete operations on records from table rows without navigating away from the list view.

Chained AJAX Calls — Use oncomplete to call another <apex:actionFunction> after the first completes, creating a sequence of server-side operations.

Common Mistakes to Avoid

Even experienced developers trip over these gotchas:

Placing actionFunction outside apex:form — This is the most common error. The component must be inside <apex:form>. If it’s outside, the JavaScript function is either not generated or silently fails.

Placing actionFunction inside iteration components — You cannot place <apex:actionFunction> inside an iteration component like <apex:pageBlockTable> or <apex:repeat>. Instead, put the <apex:actionFunction> after the iteration component, and inside the iteration put a normal JavaScript function that calls it.

reRender conflicts with rendered attribute — If the component you’re trying to reRender uses its own rendered attribute to control visibility, the reRender won’t behave as expected. Wrap the conditionally rendered content inside an always-rendered <apex:outputPanel> and use that panel’s ID in reRender instead.

Forgetting the name attribute — The name attribute is required. Without it, no JavaScript function gets generated, and your onclick handlers will throw a “function not defined” error.

Using actionFunction for non-form interactions — If you need AJAX support tied directly to a component event (like onchange on an input field), <apex:actionSupport> is often the cleaner choice. Use <apex:actionFunction> when you specifically need to call a controller method from a custom JavaScript block.

Why This Still Matters in 2026 and Beyond

You might be wondering: with Lightning Web Components (LWC) being the modern standard, is Visualforce still relevant?

The answer is yes — for now, and for longer than many expect. A huge portion of Salesforce orgs still run on Visualforce pages, especially in enterprise environments where migration is gradual. Salesforce Developer I certification exams still test Visualforce knowledge. And many consulting projects specifically require maintaining or extending legacy Visualforce functionality.

Understanding the <apex:actionFunction> component is a core competency that demonstrates you can work in real-world Salesforce environments — not just greenfield LWC projects. Employers and clients value developers who can navigate both paradigms.

Conclusion

The action function component with example is one of those Salesforce fundamentals that, once you understand it, opens up a completely different level of UI development. It gives you the power to call Apex controller methods directly from JavaScript, update specific parts of your page without full reloads, pass parameters between layers, and build genuinely dynamic user experiences in Visualforce.

To recap:

  • <apex:actionFunction> creates a JavaScript function tied to an Apex controller method.
  • It must live inside <apex:form>.
  • Use reRender to partially refresh components, apex:param to pass values, and oncomplete to chain actions.
  • Avoid placing it inside iteration components.
  • It’s distinct from <apex:actionSupport>, which attaches AJAX to a specific component event.

Ready to Go Deeper into Salesforce Development?

If this post got you excited about writing real Salesforce code, there’s a lot more ground to cover — from writing Apex triggers and test classes to building REST API integrations and deploying to production environments.

The Salesforce Apex Programming Language course on MyTutorialRack is built specifically for developers who want to move beyond theory and start building real things. You’ll work through hands-on projects that mirror what actual Salesforce developers do on the job — writing triggers, classes, unit tests, and integrations from scratch.

Whether you’re preparing for the Salesforce Platform Developer I exam or trying to land your first developer role, this course gives you job-ready skills with structured, practical guidance every step of the way. No fluff — just real Apex development, explained clearly.

Check it out and start building with confidence.

Share:

Recent Posts