15

I have a button to submit a form and invoke a managed bean action.

<h:form>
    ...
    <h:commandButton value="Submit" action="#{bean.submit}" />
</h:form>

But when I press the button it refreshes the whole page and sometimes also changes the URL.

Is there some way to not refresh the page and still invoke the action?

BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452
Valter Silva
  • 15,646
  • 48
  • 123
  • 210
  • For your consideration, you may want to look at the [Primefaces PhotoCam](http://www.primefaces.org/showcase-labs/ui/photoCam.jsf) component. I believe it makes use of HTML5 rather than Flash though. – maple_shaft Jan 24 '12 at 15:00
  • Primefaces PhotoCam sure looks Flash based to me (which is wise since none of the major browsers support camera access through HTML(5)/JavaScript, as far as I know only Opera currently supports it). – Lars Blåsjö Jan 24 '12 at 21:45
  • PF photoCam uses native access now where available – Kukeltje Sep 29 '15 at 07:31

1 Answers1

24

Make use of Ajax. It's a matter of nesting <f:ajax> inside the command button of interest.

<h:form>
    ...
    <h:commandButton ...>
        <f:ajax execute="@form" render="@none" />
    </h:commandButton>
</h:form>

Particularly the render="@none" (which is the default value anyway, you could just omit the attribute altogether) will instruct JSF to re-render just nothing after the submit. If you intend to re-render only a specific component instead of the whole page, then you could also specify the ID of that specific component in render attribute.

<h:form>
    ...
    <h:commandButton ...>
        <f:ajax execute="@form" render="result" />
    </h:commandButton>
    ...
    <h:panelGroup id="result">...</h:panelGroup>
</h:form>

If you're already using PrimeFaces, then it's a matter of simply using <p:commandButton> instead of <h:commandButton>. It uses by default ajax already, so you don't need to nest in a <f:ajax>. You only need to remember to use attribute names process and update instead of execute and render.

<h:form>
    ...
    <p:commandButton ... update="result" />
    ...
    <h:panelGroup id="result">...</h:panelGroup>
</h:form>

The execute attribute defaults to @form already, so it could be omitted.

See also:

Community
  • 1
  • 1
BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452