1

I have a simple VF page:

<apex:page controller="OpportunityExt">  
 <script type="text/javascript">
 function initialize(){
     alert('Value ' + '{!abc}');
 }
 </script> 
 <apex:form > 
          <apex:commandButton id="saveBtn" action="{!search}" value="Search" oncomplete="initialize();"/>
  </apex:form> 

</apex:page>

Controller class:

public class OpportunityExt {

    public void search() {
        abc='hello';
    }

    public string abc{get;set;}
    public OpportunityExt() {
       // can set the abc value only here.

    }

}

The problem:

I am trying to set the value of abc string in search() method and access the value in the javascript method initialize() . But this does not work. I get an empty value in the alert message. However when I set the abc value in Constructor I get a the value in alert message.

How can set the value of a controller variable and access it in javascript intialize() method.

1 Answer 1

2

The value of {!abc} in your javascript is set when the page is first loaded, after running the constructor. To get the updated value, you'll need to cause a a rerender of your javascript, putting the correct value on your page.

For example:

<apex:page controller="OpportunityExt">  

 <apex:form>

    <apex:outputPanel id="Something">
        <script type="text/javascript"> 
            function initialize() {
                alert('Value ' + '{!abc}');
            }
        </script> 
    </apex:outputPanel>

    <apex:commandButton id="saveBtn" rerender="Something" action="{!search}" value="Search" oncomplete="initialize();"/>

  </apex:form> 

</apex:page>

The oncomplete="initialize();" is pure javascript, and only happens when the buttons action has completed. The reRender matters because it refreshes the outputPanel. When a component is rerendered, it will update any merge fields in the component ({!abc} in this case), and will use the current value of that variable on the server side.

{!abc}'s value is set by the action, then the value is reset on the page, then the oncomplete="initialize();" runs, using the newly set value in the javascript. The order of operations here is very important.

3
  • Great. Wanted to understand that why do we need to reRender when we are already calling the function on Oncomplete. So is it like we are calling the Initialize() method twice?
    – Arnold
    Sep 25, 2017 at 17:36
  • The function is only called once, after the action and the rerender have completed. See my edit to the answer. Sep 25, 2017 at 17:52
  • Well explained.!
    – Arnold
    Sep 25, 2017 at 18:02

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .