Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSF form post with AJAX

Tags:

ajax

jsf-2

I want the following form to use AJAX. So the comments are shown after clicking the command button and without reloading the page. What needs to be changed, using Java Server Faces 2.0?

Functionality: This form provides an inputText to define a topic. After pressing the commandButton, it is searched for comments regarding this topic. Comments are shown in a dataTable, if there are any. Otherwise Empty is shown.

<h:form id="myForm">
    <h:outputLabel value="Topic:" for="topic" />
    <h:inputText id="topic" value="#{commentManager.topic}" />
    <h:commandButton value="read" action="#{commentManager.findByTopic}" />
    <h:panelGroup rendered="#{empty commentManager.comments}">
        <h:outputText value="Empty" />
    </h:panelGroup>
    <h:dataTable
        id="comments"
        value="#{commentManager.comments}"
        var="comment"
        rendered="#{not empty commentManager.comments}"
    >
        <h:column>
            <h:outputText value="#{comment.content}"/>
        </h:column>
    </h:dataTable>
</h:form>
like image 276
Matthias Avatar asked Jun 24 '11 18:06

Matthias


2 Answers

You need to tell the command button to use Ajax instead. It's as simple as nesting a <f:ajax> tag inside it. You need to instruct it to submit the whole form by execute="@form" and to render the element with ID comments by render="comments".

<h:commandButton value="read" action="#{commentManager.findByTopic}">
    <f:ajax execute="@form" render="comments" />
</h:commandButton>

Don't forget to ensure that you've a <h:head> instead of a <head> in the master template so that the necessary JSF ajax JavaScripts will be auto-included.

<h:head>
    ...
</h:head>

Also, the element with ID comments needs to be already rendered to the client side by JSF in order to be able to be updated (re-rendered) by JavaScript/Ajax again. So best is to put the <h:dataTable> in a <h:panelGroup> with that ID.

<h:panelGroup id="comments">
    <h:dataTable rendered="#{not empty commentManager.comments}">
        ...
    </h:dataTable>
</h:panelGroup>

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"
like image 129
BalusC Avatar answered Oct 21 '22 17:10

BalusC


You need to modify your button:

<h:commandButton value="read" action="#{commentManager.findByTopic}">
    <f:ajax render="comments" />
</h:commandButton>

This means, when the button is clicked, the action is executed, and the dataTable will be rendered and updated. This only works if the backing bean is at least view-scoped.

like image 40
Björn Pollex Avatar answered Oct 21 '22 17:10

Björn Pollex