apex:commandButton with Return Value

Below you can see a sample code that can be used to return a value from an Apex controller to a Visualforce page when calling a controller function from an apex:commandButton. This approach doesn’t require you to use @RemoteAction (i.e. static methods), so you doesn’t lose the stateful nature of your page, and your controller’s method can access all the variables within that controller instance.

Visualforce Page:

<apex:page controller="ReturnController">

    <apex:form >
        <apex:commandButton action="{!callMe}"
                    oncomplete="processReturnedValue({!valueReturned}); "
                    value="Click Me!"/>
    </apex:form>

    <script>
        var processReturnedValue = function(val){
            alert('Returned Value: ' + val);
        };
    </script>

</apex:page>

Controller:

public class ReturnController {

    public Integer valueReturned {get; set;}

    public ReturnController(){
        this.valueReturned = 0;
    }

    public void callMe(){
        this.valueReturned++;
    }

}

That’s it. Try it, it works. Let me know in the comments if there are any drawbacks to this approach. I’m always open to constructive critique.

P.S. The same would work for apex:actionFunction that you can call from JavaScript, see below:

<apex:actionFunction action="{!callMe}" name="actionFuncName" 
    oncomplete="processReturnedValue({!valueReturned}); "/>
Written on May 15, 2016