Ajax in Visualforce page

In Visualforce, you can use Ajax (Asynchronous JavaScript and XML) techniques to perform asynchronous requests to the server without refreshing the entire page. This allows you to update specific parts of the page dynamically, providing a smoother and more responsive user experience. Here's how you can use Ajax in Visualforce pages:

Using <apex:actionFunction>:

<apex:actionFunction> allows you to define a JavaScript function that invokes an Apex controller method without a full page refresh. It's typically used to perform server-side actions based on user interactions.

Example

<apex:page controller="MyController">
    <apex:form>
        <apex:commandButton value="Click Me" onclick="doAction(); return false;"/>
        <apex:actionFunction name="doAction" action="{!myControllerMethod}" rerender="outputPanel"/>
    </apex:form>
    <apex:outputPanel id="outputPanel">
        <!-- Content to be updated -->
    </apex:outputPanel>

</apex:page>

Using <apex:actionSupport>:

<apex:actionSupport> allows you to associate an action with a Visualforce component, such as <apex:inputField> or <apex:commandButton>, and execute it without a full page refresh.

Example:

<apex:page controller="MyController">
    <apex:form>
        <apex:inputText value="{!myValue}">
            <apex:actionSupport event="onchange" action="{!myControllerMethod}" rerender="outputPanel"/>
        </apex:inputText>
    </apex:form>
    <apex:outputPanel id="outputPanel">
        <!-- Content to be updated -->
    </apex:outputPanel>
</apex:page>

Using JavaScript Remoting:

JavaScript Remoting allows you to make direct calls to Apex controller methods from JavaScript code on the client side. It provides a powerful way to perform server-side actions asynchronously.

Example

<apex:page controller="MyController">
    <script>
        function fetchData() {
            MyController.myRemoteMethod(function(result, event) {
                if (event.status) {
                    // Process result
                } else {
                    // Handle error
                }
            });
        }
    </script>
    <apex:form>
        <apex:commandButton value="Fetch Data" onclick="fetchData(); return false;"/>
    </apex:form>
</apex:page>


Comments

Popular posts from this blog

Introduction to Salesforce Agent Script: Build Predictable AI Agents

Anti-Patterns in Salesforce Agentforce: What to Avoid When Building AI Agents

MCP vs. Traditional APIs: Choosing the Right Integration Approach