Salesforce: Invoking Visualforce Action via Javascript

We did a lot of Salesforce implementation and customisation work recently. We came across a situation where we need to perform some action in Javascript and invoke a  VisualForce action after that. We did some research and found a useful component <apex:actionFunction>. This component exposes a controller method as a Javascript function so that we can invoke it by using Javascript in our  VisualForce page. Here is a simple example of how to do this.

 

Visualforce Controller

public class VisualforceJavascriptDemo{

    public string myparam {get; set;}

    public VisualforceJavascriptDemo(){
        myparam = 'Initial value';
    }

    public PageReference myJSAction(){
        return null;
    }
}
In the controller, we create the following:
  • a variable called “myparam” – this will be defined in <apex:param> component within <apex:actionFunction> to hold the value passed by Javascript in  VisualForce page
  • an action function called “myJSAction” – this will be defined in action attribute in <apex:actionFunction> as an action function to be invoke by Javascript in VisualForce page

 

Alright, that’s what we have in the controller. The following will be the code that we have in the VisualForce page:-
    
        
            
        

        
             - Invoke action here
        

        
    

As you can see that we define the <apex:actionFunction> as discussed above. Please take note that the “name” attribute is important as that will be the Javascript function name. We named it as “myJSAction” here.

Yup, we are done. Now you just need to call the myJSAction anywhere on the VisualForce page (e.g, via onclick, onchange action or Javascript function) and you should see the magic!