Passing Variables from Apex to JavaScript

Sometimes we need to pass variables from apex to javascript. Here is an example to pass variables from apex to javascript. In below example I’m invoking one apex method using action function. In the apex method I’m defining the apex variable value. On complete of action function I’m invoking one javascript method and using the apex variable in the javascript method.

Visualforce Page:

<apex:page controller="SampleController">  
    <apex:form>
        <apex:outputPanel id="jspanel"> 
            <script>  
            function onCompleteMethod() {
                alert('{!message}')
            }
            </script>
        </apex:outputPanel>
        <apex:actionFunction name="afHelloWorld" action="{!HelloWorld}" rerender="jspanel"/>
        <apex:commandButton onclick="afHelloWorld();" oncomplete="onCompleteMethod()" value="Click me"/>
    </apex:form>
</apex:page>

Apex Class:

public class SampleController {
    
    public String message {get;set;}
    
    public pageReference HelloWorld() {
        message = 'Hello World!!';
        return null;
    }   
}