Skip to content
javahacks.dev
JavaServer Faces

JSF AJAX Partial Page Updates With the Ajax Tag Explained

Use JSF AJAX with f:ajax: the execute and render attributes, event triggers, listeners, ids inside naming containers and common reasons nothing updates.

6 min read
Summarize in AI
Flat illustration of a browser page built from server-side components, with the OpenJDK, CSS and HTML5 logos.

Plain JSF submits the whole form and renders the whole page. f:ajax changes that: it turns an event on a component into an asynchronous request that sends only some components to the server and replaces only some components in the browser. The result is a page that updates a dropdown or a message without a reload. The mechanism rests on two attributes, execute and render, and nearly every AJAX problem in JSF is a wrong value in one of them. This post uses Jakarta Faces 4, and the same attributes exist on PrimeFaces' p:ajax.

A dependent dropdown

XML
<h:form id="addressForm">
  <h:selectOneMenu id="country" value="#{addressBean.country}">
    <f:selectItems value="#{addressBean.countries}" />
    <f:ajax listener="#{addressBean.loadCities}" render="city" />
  </h:selectOneMenu>

  <h:selectOneMenu id="city" value="#{addressBean.city}">
    <f:selectItems value="#{addressBean.cities}" />
  </h:selectOneMenu>
</h:form>
java
@Named
@ViewScoped
public class AddressBean implements Serializable {

    private String country;
    private String city;
    private List<String> cities = List.of();

    public void loadCities(AjaxBehaviorEvent event) {
        cities = cityService.citiesIn(country);
    }
    // getters and setters
}

When the user changes the country, the browser sends an AJAX request. The server applies the new country value, calls loadCities, renders the city component and sends back just its markup, which replaces the old one in place. The rest of the page is untouched, so scroll position, other fields and focus survive. The bean is @ViewScoped on purpose: a request-scoped bean would lose its cities between the request that loads them and the next one, and bean scopes explains why.

Execute and render

execute lists the components that are processed on the server: their submitted values are converted, validated and applied to the model. render lists the components whose markup is replaced from the response. The defaults, when f:ajax is nested in a component, are execute="@this" and render="@none", so by default only the component that fired the event is processed and nothing is redrawn. A listener that changes data and a missing render is the first reason nothing seems to happen.

KeywordMeaning
@thisThe component that triggered the event
@formEvery component in the enclosing form
@allThe whole view
@noneNothing
@parentThe parent of the triggering component (PrimeFaces and newer Faces)

You can mix keywords and ids with spaces: execute="@this country" render="city summary". Choose the smallest execute that works. A wide one such as @form runs validation on every field, so a required field the user has not reached yet produces an error message the moment they change an unrelated dropdown. If the AJAX call fails validation, the listener never runs and the model is not updated, which looks exactly like the call doing nothing.

Finding the right id

Ids in execute and render are resolved relative to the closest naming container, usually the enclosing h:form. Inside the form above, render="city" works. From outside the form, you must use the absolute form with a leading colon, render=":addressForm:city", where the separator is a colon. The browser's developer tools show the real id of the element in the rendered page, and that string, with the form prefix, is what a reference must resolve to. A component inside a ui:repeat or a data table has a row index in its id, and the reference must go through the naming container of the table.

A second trap: a component with rendered="false" does not exist in the page, so it cannot be a render target, and an update to it silently does nothing. Wrap it in a container that is always rendered and put the id on the container:

XML
<h:panelGroup id="shippingBlock">
  <h:inputText id="postcode" value="#{order.postcode}" rendered="#{order.needsShipping}" />
</h:panelGroup>
<h:selectBooleanCheckbox value="#{order.needsShipping}">
  <f:ajax render="shippingBlock" />
</h:selectBooleanCheckbox>

Events

f:ajax picks a sensible default event for the component: valueChange for inputs, action for buttons. Set another with event. A search box that filters as you type uses event="keyup", and you will want to limit the traffic, because every keystroke is a request. PrimeFaces adds a delay attribute for this, and plain Faces needs a small script or a different component. Other useful attributes are onevent and onerror, JavaScript callbacks for showing a spinner and handling a failed request, and listener, the method to call on the server.

A page that must keep state

AJAX updates the server-side view state as well as the browser. That is why the bean scope matters, and why a session that has expired produces the error described in [ViewExpiredException](/library/viewexpiredexception-fix-javaserver-faces). On the first AJAX call after a timeout, the browser gets a response it cannot apply. Handle it by configuring an error page or redirecting to the login. Also remember that the update replaces markup, so any JavaScript widget attached to the old element is gone unless the component library re-initialises it. PrimeFaces components handle this for their own markup, and hand-written scripts do not.

Validation and conversion messages need a place to appear. Include the message component in render, as in render="city cityMessage", or the user fixes nothing because they see nothing; see validation, converters and messages.

Debugging checklist

When an AJAX call does nothing, work down the list. Does the request appear in the browser network tab? If not, the event never fired. Does the response contain a partial-response with an update for your id? If not, the id did not resolve, or render is empty. Did validation fail? Look for a message. Did the listener run? Put a log line in it. Setting javax.faces.PROJECT_STAGE to Development, now jakarta.faces.PROJECT_STAGE, adds more diagnostics to the page, including the AJAX error details in the browser.

Ajax and validation together

A common surprise is an AJAX call that is blocked by a validation error on a field that has nothing to do with it. This follows from the execute list: every component in it goes through the full validation phase. Restrict execute to the fields that the update needs, so the dependent dropdown validates only the country, not the required email field further down the form. When the listener needs the value of a field that is not in execute, the model does not have it, and the listener sees the old value, which is the mirror image of the same mistake. The two attributes together are a contract: what is sent, and what is redrawn.

When you do want validation to be skipped, for example for a Cancel button that uses AJAX, set immediate="true" on the button. The action then runs in an earlier phase, before conversion and validation of the other fields.

When AJAX is the wrong tool

A change that touches most of the page is simpler as a normal navigation. Large lazy-loaded tables should use the component library's own lazy model and not hand-written AJAX, see lazy loading in PrimeFaces data tables. The attributes are defined in the Jakarta Faces 4.0 specification, and the PrimeFaces variant is documented under AJAX in PrimeFaces.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.