access controller variable in javascript

Is there any way to access controller variable set in a Method in Javascript.
In the example above the value is set in constructor.
But when I set it in a method it is showing as NULL in Javascript

In controller:

public class abc {
    public string varA { get;set; }
    public void fn(){
        varA='hello';
    }
}

In VFPage:

function hello(){
    var bool = '{!varA}';
    alert(bool);
}

The alert statement in the VF Page(i.e bool) is displayed as null.
Can you please help how to access a variable set from a method instead of constructor?

Answer

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);
}

Attribution
Source : Link , Question Author : sfdc , Answer Author : Mark Pond

Leave a Comment