Search code examples
javascriptjsfrichfaces

jsFunction's data is undefined when event starter is inside the form


here is my situation:
I'd like to test if anyway to link the java bean and xhtml, so I use the richfaces, a4j:jsFunction to deal it.
I succeed -- in some limit, that the event starter have to fire OUTSIDE the form, so WEIRD !!
there are 3 parts in my code: xhtml、js、java
xhtml:

<button id="succeed" onclick="showMessage()"> succeed_test </button>
<!-- this is the succeeded button -->  

<h:form id="form1" prependId="true" >

        <button id="fail" onclick="showMessage()"> fail_test </button>
        <!-- this is the failed button -->  

        <a4j:jsFunction 
            name="showMessage"
            data="#{javaBeanTest.showThings()}"
            oncomplete="presentData(data)" 
            immediate="true" />

</h:form>

js:

function presentData(data){
    alert(data);
}

java:

@Name("javaBeanTest")
public class JavaBeanTest implements Serializable{
    public boolean showThings(){
        System.out.println("--JavaBeanTest.showThings()");
        return true;
    }
}

when clicking the 「succeed_test」 button, I got a 「true」 alert and 「--JavaBeanTest.showThings()」 on console, but only got 「undefined」 alert and 「--JavaBeanTest.showThings()」 on console while clicking 「fail_test」 button.

obviously the DIFFERENCE is of inside or outside the form .....

CONFUSED !!!! PLEASE !!!

ps.in my richfaces version, it works with 「data」 instead of 「event.data」, should be 3.x
JDK 1.6
JBDS 4.1.0GA
seam 2.2
JSF 1.2


Solution

  • In your case HTML button submits the form if it is inside of one (behavior may differ from browser to browser). You need to specify explicitly the button type or prevent default submit behavior, e.g.:

    <button id="fail" type="button" onclick="showMessage()">does not fail anymore</button>
    

    or

    <button id="fail" onclick="showMessage(); return false;">does not fail anymore</button>
    

    There is a recommendation by W3C to always specify the type attribute:

    Tip: Always specify the type attribute for the element. Different browsers may use different default types for the element.

    Refer to: http://www.w3schools.com/tags/att_button_type.asp