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);
}
  • is the script in the something rerendered portion of the page? – martin Aug 8 '16 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 '16 at 15:37
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.

  • You were correct, it was the placement of the script + reRendering the script. Thank you very much! – Aerin C Aug 8 '16 at 16:02
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');

Hope it helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.