Calling Managed Bean Method From JavaScript

65,393

Solution 1

You have a few options. If you are using JSF 2.0 you can build a composite component around these area tags.

The easiest way however would be to invoke a hidden JSF input button.

<h:commandButton id="hdnBtn" actionListener="#{personBean.method}" style="display: none;" />

This will render as an input HTML element on the page that you can access from Javascript and invoke its click event.

onclick="jQuery('#form:hdnBtn').click();"

Solution 2

If you use primefaces, you don't need jquery. You use remoteCommand with a name attribute, and call that name from javascript, so:

<area... onclick="somejavascript();"... />

<p:remoteCommand name="myCommand" actionListener="#{personBean.method}" style="display: none;" />

Javascript:

function somejavascript(){
   myCommand();
}

Solution 3

If you want complete ADF Faces solution you can try this:

function doClick(){
   var button = AdfPage.PAGE.findComponentByAbsoluteId("aButton");
   ActionEvent.queue(button,true);
}

Solution 4

If you use Seam, Remoting can do this for you: http://docs.jboss.org/seam/2.2.0.GA/reference/en-US/html/remoting.html

Another approach would be do expose the methods as REST services, and call them from your JavaScript using something like jQuery. Here's a good article on this approach: http://coenraets.org/blog/2011/12/restful-services-with-jquery-and-java-using-jax-rs-and-jersey/

Solution 5

This is the most up to date answer, for Java EE 8 (JSF 2.3) use <h:commandScript> this will create a javascript function which will under the hood invoke the jsf backing bean method, and because it's a javascript you can invoke it from your js code

example jsf

<h:form>
<h:commandScript id="submit" 
                 name="jsFunction"
                 action="#{bean.method}"/>
</h:form>

and the js code

</script>
        function invoke()
           {
                jsFunction();
           }
    </script>

for more visit Ajax method invocation

Share:
65,393
Jason
Author by

Jason

Updated on July 09, 2022

Comments

  • Jason
    Jason almost 2 years

    I have an application with a client-side image map with multiple sections defined. I need to call a method in the Managed Bean from the <area> onclick attribute.

    This doesn't work:

    <area id="ReviewPerson" shape="rect" coords="3, 21, 164, 37" href="#" 
        onclick="#{personBean.method}" alt="Review Person" id="reviewPersonArea"
        title="Review Person" />
    

    Since my hands are tied on the image map (unfortunately), how can I call a managed bean method from within the <area> tag?