Search code examples
javajqueryajaxjsffacelets

Ajax not working right in JSF with a jquery slide


I have this application written in JSF 2.0 facelets and it has the following code that supposed to display some content in an area which a jQuery slide controls, meaning that you press a button that displays that area and press it again to hide it

<f:ajax render="messageID">
      <h:form id="myform" styleClass="form1" >
          <h:message id="messageID" for="signinemail" class="messageforlogin"/>
          <h:panelGrid styleClass="loginpanel" columns="2" cellspacing="4">

          <h:outputText value="Email: "/>
          <h:inputText class="textboxes"  size="20" id="signinemail" 
                      value="#{signinBean.email}" 
                      validatorMessage="Invalid Email, Try Again">
              <f:validateRegex pattern="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"/>

          </h:inputText>

As you can see there is an error message that should be displayed if the email is not typed correctly, and as i said before this area is controlled with a jquery.slidetoggle function and button that makes it a slide to input the stuff in,

The thing is when the use presses the submit button(not shown here) the slide freezes and no error message is displayed,When i remove the "ajax" the message is displayed but the slide disappears and you have to press the toggle button again to see the slide with the error messages, i have done this in the same page but with out a slide and it wokrs very fine.

Is there away to display the slide and the error messages on it ???


Solution

  • The jQuery script which is responsible for setting the slides should be re-executed when the JSF ajax request completes, simply because the ajax response changes/replaces elements in the HTML DOM tree with new elements retrieved from the server which in turn of course do not contain those jQuery-initialized event handlers anymore. The jQuery script is not auto-executed everytime when the ajax request completes, but only whenever you refresh the page.

    You just need to re-invoke your jQuery function in the JSF ajax event callback handler as follows:

    jsf.ajax.addOnEvent(function(data) {
        if (data.status == "success") {
            yourjQueryFunctionWhichAddsTheSlideEvents();
        }
    });
    

    An alternative is to use OmniFaces' <o:onloadScript>.

    <o:onloadScript>yourjQueryFunctionWhichAddsTheSlideEvents();</o:onloadScript>
    

    This way you also don't need a $(document).ready() anymore.