0

In my JSF page I have a hidden form with an inputText, outputText and submit button. I'm using a script which on certain events fills the inputText and performs a click on the button. The button calls a method in a backing bean in which I need to do some actions and then set the value of the outputText. To do it I find the UIOutput component and set its value. In my javascript I need to perform some other action after the button is clicked but the problem is that it may take some time for the action to be completed and the outputText to be filled with the return value. So the next action in the javascript does not read the correct value. I thought of adding a change event on the outputText so to perform my action only after the value is updated but I have the same problem as this JS Events: hooking on value change event on text inputs.

Community
  • 1
  • 1
user579674
  • 2,159
  • 6
  • 30
  • 40

1 Answers1

2

So, if you were using an a4j:commandButton, you could just use the oncomplete attribute to some JS code that would execute after completing the AJAX request.

Since you are using a h:commandButton with an f:ajax, the way to do that is to use the f:ajax attribute onevent, and check if it succeeded like this:

<script>
    function doWhatever(e){
        if(e.status == 'success'){
            doYourThingHere();
        }
    }
</script>
<h:commandButton action="#{someMB.someAction}">
    <f:ajax ... onevent="doWhatever" />
</h:commandButton>

If you use Richfaces, you may want to take a look at a4j:ajax component, see this question.

UPDATE: removed incorrect else that assumed request didn't succeeded. See the answer to this question to see other meanings for the status attribute.

Community
  • 1
  • 1
Elias Dorneles
  • 22,556
  • 11
  • 85
  • 107
  • The alert message in your `else` is not entirely correct. See also http://stackoverflow.com/questions/8570592/trigger-jsf-ajax-before-javascript/8574487#8574487 – BalusC Jul 04 '12 at 18:27
  • @BalusC You're right, I'm going to fix that! Thanks for pointing it out! – Elias Dorneles Jul 04 '12 at 18:58
  • @user579674 You're welcome, I'm glad to help! Please note the update, I've removed the else condition with the alert, cause I was erroneously assuming that the request didn't succeeded. – Elias Dorneles Jul 04 '12 at 19:04
  • The alert was not entirely correct in the else as it was called randomly (I think so) but as a matter of fact I'm still using the else to render a progress bar notifying the user that there is an ongoing action that needs some time and it seems to work as intended. – user579674 Jul 04 '12 at 19:36
  • @user579674 Please see the answer BalusC linked above (and which I linked in the update too). The status can also be 'begin' (meaning before the request is sent) and 'complete' (meaning after the response is received, but before the DOM is updated -- rerendered) – Elias Dorneles Jul 04 '12 at 20:48