Search code examples
javascriptajaxjsfrichfaces

How to call bean method from javascript function using a4j:ajax or a4j:actionListener?


I am using JSF, richfaces 4 stuff and i want to call a bean method when javascript function trigger.


Solution

  • You can use <a4j:jsFunction> , which allows you to perform Ajax requests to invoke the bean method directly from JavaScript code , and the response can be returned in a JSON format to use in a client JavaScript calls.

    Please note that <a4j:jsFunction> is required to be inside a <h:form> . For example, you define the a4j:jsFunction likes this :

    <h:form> 
        <a4j:jsFunction name="myJsFunction"  action="#{bean.someAction}" reRender="xxxxx"/>
     </h:form>
    

    A javascript function which name called myJsFunction() is created and it will invoke someAction() on the bean when being called.

    For example , in your javascript function :

    <script type="text/javascript">
    function yourJavaScriptFuntion() {
        ..............;
        myJsFunction();  //bean.someAction() will invoke here
        ..............;
    }