How make commandButton not fully refresh page? How to use f:ajax?

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?


Solution 1:

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:

  • Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes
  • How to find out client ID of component for ajax update/render? Cannot find component with expression "foo" referenced from "bar"
  • Why do I need to nest a component with rendered="#{some}" in another component when I want to ajax-update it?