5

When my javascript function recieves a value from a controller boolean, it gets "false" instead of "true". Meanwhile, a System.log debug states that the boolean is "true". What could be causing this? There is much more code inside of the apex controller than I show below, so I'm thinking that possibly the javascript runs before the apex function is finished.

Here is the gist of the code:

VisualPage and Javascript

 <apex:actionSupport event="onchange" action="{!myAction}" reRender="something" oncomplete="myFunction();" />

 <script type="text/javascript">
 function myFunction(){
   window.alert({!myBoolean});
 }
 </script>

Apex Controller

public void myAction(){
  myBoolean = true;
  System.debug(myBoolean);
}
2
  • is the script in the something rerendered portion of the page?
    – martin
    Aug 8, 2016 at 15:26
  • I'm not quite sure what you mean by that, but in summary "something" does not rely on the "myFunction" . ReRendering is working though.
    – Aerin C
    Aug 8, 2016 at 15:37

2 Answers 2

4

When the page loads, the {!myBoolean} expression gets the value of myBoolean at the time of the page load. So essentially the javascript function in your page would be:

function myFunction(){
   window.alert(false);
}

If the value of myBoolean is changed in the controller, you would also have to rerender the javascript function, or else it would remain as alert(false);

Moving the javascript function inside the something block should solve your problem.

2
  • You were correct, it was the placement of the script + reRendering the script. Thank you very much!
    – Aerin C
    Aug 8, 2016 at 16:02
  • I am also facing the same issue. Can you please elaborate on the fix. I am saving boolean correctly in custom settings. But when vf Loads it is returning false.
    – user75427
    Mar 8, 2020 at 18:52
0

We should not bind Apex objects/variables directly in JavaScript (like you have {!myBoolean}). Previously had lots of issues with this and finally refactored the code to eliminate it. Instead use JavaScript Remoting or the Ajax Toolkit.

Not sure of the reason, but the value of the apex variable is what it is set in constructor or in getter for the first time. So javascript not getting the latest value after the execution of apex method.

Another workaround is using an <apex:inputHidden>, assign the variable to it and get its value using getElementById

<apex:inputhidden id="myBoolean" value="{!myBoolean}" />

var mybool = document.getElementById('myBoolean').value;

Hope it helps.

You must log in to answer this question.

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