access controller variable in javascript
Accessing controller properties uses the usual get & set syntax.
Set in a constructor and retrieved using the shorthand notation
public class YourController {
public string varA { get; set; } // use the proper type
public YourController() {
varA = 'Some text';
}
}
or
Retrieved from the getNNN mechanism
public class YourController {
public YourController() { }
public string getvarA() {
return 'Some text';
}
}
or
Retrieved from a shorthand getter which calls a method in the controller
public class YourController {
public YourController() { }
public string varA { get { return doIt(); } }
private string doIt() {
return 'Some text';
}
}
VF Page - JavaScript function - controller property reference will work with any of the above examples:
<script>
function hello(){
var theControllerValue = '{!varA}';
alert(theControllerValue);
}
</script>
The rendered source for the page, which you can go look at in the browser, will look like this after the substitution for the controller variable has been made:
function hello(){
var theControllerValue = 'Some text';
alert(theControllerValue);
}
You have to re-render the script in order to have the value appear. Consider the following:
Controller
public class Controller {
public String varA { get; set; }
public void updateVarA() {
varA = 'Hello';
}
}
Page
<apex:page controller="Controller">
<apex:form id="form">
<apex:outputText id="script">
<script>
function hello() {
var helloWord = "{!JSENCODE(varA)}"
alert(helloWord);
}
</script>
</apex:outputText>
<apex:actionFunction action="{!updateVarA}" reRender="script" name="callUpdateA"/>
<button onclick="callUpdateA()">Call Update A</button>
<button onclick="hello()">Say Something!</button>
</apex:form>
</apex:page>
How It Works
We don't initially set any value (there's no constructor at all), so when you click on Say Something, it will alert "null". Clicking "Call Update A" calls "callUpdateA()", which invokes the actionFunction, which updates the page. The trick here is that the actionFunction re-renders the script-- the new value will be available in the function after the call completes. Finally, clicking on "Say Something" again will result in an alert that reads "Hello".
This isn't the only way to do this, but is probably one of the easier ways to accomplish this task.