How to refresh Apex variable inside Javascript in Visualforce page?

How to refresh Apex variable inside Javascript in Visualforce page?

To refresh Apex variable inside Javascript in Visualforce page, move the Javascript inside apex:outputPanel and rerender the apex:outputPanel to refresh Apex variable inside Javascript.

Don’t keep the Javascript snippet in the beginning of the page, move it to the last before </apex:page> tag.

Sample Code:
Visualforce Page:
<apex:page controller=”SampleVFPageController”>
    <apex:form id=”pageForm”>
        strTemp is {!strTemp}<br/>
        <apex:commandButton value=”Testing” reRender=”pageForm,JSPanel”>
            <apex:param value=”Test 2″ assignTo=”{!strTemp}”/>
        </apex:commandButton>
    </apex:form>
    <apex:outputPanel id=”JSPanel”>
        <script type=”text/javascript”>
            console.log( ‘{!strTemp}’ );
        </script>
    </apex:outputPanel>
</apex:page>
 
Apex Class:
public class SampleVFPageController {
    
    public String strTemp { get; set; }
    
    public SampleVFPageController() {
        
        strTemp = ‘Test 1’;
        
    }
    
}
 
Output:
 

Leave a Reply