Learning JSF2: Ajax in JSF – using f:ajax tag

This is a third post in Learning JSF 2 series. The first one on Managed Beans can be found here and second one on navigation can be found here

As you probably know JSF 2 is a major upgrade over JSF 1.2. One of the major additions to this version of JSF is standard Ajax support. This article covers Ajax features in JSF 2. If you are familiar with RichFaces and specifically the a4j:support tag then learning how to use Ajax features in JSF 2 is going to be very easy. Many concepts and features are being carried over from RichFaces.  Let’s start. 

JSF 2 comes with one tag that provides Ajax functionality. The tag is called f:ajax (sounds familiar to a4j:support – right?) When I do RichFaces trainings, I like to divide the core ideas into three parts: sending an Ajax request, partial view rendering and partial view processing. I will use the same approach here. 

Sending an Ajax request

JSF comes with one tag to send an Ajax request, the tag is called f:ajax. This tag is actually a client side behavior (here is a great post by Andy Schwartz on JSF 2 client behaviors). Being a behavior implies it’s never just used by itself on a page, it is always added as a child tag (behavior) to another UI component (or can even wrap several components). Let’s use a small echo application to demonstrate usage of this tag. 


   
      
         
      
      
   

Code snippet above takes care of firing an Ajax request based on onkeyup event. Notice the actual event name is keyup. This takes care of firing an Ajax request. Next we need to figure out how to do partial view rendering. 

Attribute Description
event String on which event Ajax request will be fired. If not specified, a default behavior based on parent component will be applied. The default event is action for ActionSource (ie: button) components and valueChange for EditableValueHolder components (ie: input). action and valueChange are actual String values that can be applied applied event attribute. 

HTML Tables

Note: In RichFaces 3.x, you specify the event with onevent, for example onkeyp. In JSF 2, you only specify the actual action: keyup.

Partial view rendering

With JSF 1.2 (and without RichFaces) every request would render the entire view back to us. That was simple, we didn’t have to worry which parts of the JSF view we want to be updated. Of course the basic concept behind Ajax is to only update those parts of the page that we actually need to. In order to accomplish this, we should only render those components on the server whose markup we want to update in browser. What all this means is we now need to specify which components in JSF view we want to render back. Partial view is still rendered on the server. Some updated portion is sent as XML to the browser where the DOM is updated.  Our example is rather simple, there is just one component with id text. f:ajax tag has render attribute which points to id’s of components to be rendered (or rerendered) back. It could also take an EL expression. Adding it to our example, it looks like this:


   
      
         
      
      
   

If you have been using RichFaces, than the same attribute in RichFaces is called reRender. The event that is specified via event attribute must be an event that the parent component supports. If you look at the generated HTML, you will see something like this:


If you specify an event that is not available on the parent component, an error message will be displayed when you run the page. 

That’s it. Here is the bean code in case you want to run this page:

@ManagedBean(name = "bean")
public class Bean {
   private String text; // getter and setter
   ...
}

Let’s say we also want to show and update a counter that shows the length of a string we entered. Adding new property to bean:

private Integer count; // getter and setter

Also adding Ajax listener to do the counting, notice that method takes a new AjaxBehaviorEvent object: 

public void countListener(AjaxBehaviorEvent event) {
   count = text.length();
}
Attribute Description
listener Listener method to invoke during Ajax request. 

Updating the page:


   
      
         
      
      
      
   

Notice that we added count id to render attribute. You use space as a separator for id’s. 

In our examples above we actually specified on which even to fire an Ajax request. As it turns out we don’t have to specify an event. If we don’t specify one, each UI component has a default event on which Ajax request would be send. Taking h:inputText, the default Ajax event is onchange. Our example would almost work however, instead of onkeyup, you would now have to tab out or click outside the input field to fire the Ajax request:  So, we could have written our example like this (without event attribute):


   

Attribute Description
render Determines id’s of components to be rendered. 
 

In our example, render pointed to actual component id we want to render back. render attribute could be set to the following values: 

Possible values for render attribute Description
@all Render all components in view
@none Render no components in view (this is also the default value if render is not specified)
@this Render only this component, the component that triggered the Ajax request
@form Render all components within this form (from which Ajax request was fired)
id’s One or more id’s of components to be rendered
EL EL expression which resolves to Collection of Strings

render could also point to EL expression. In this case it’s possible to determine which components to render in run time. Here is how it works when using EL:

  • You bind render=”#{bean.renderComponents}”. Initial page is rendered. #{bean.renderComponents} is resolved during page rendering, for example to id’s compId1 and compId2.
  • On next Ajax request, compId1 and compId2 will be rerendered. During this request, #{bean.renderComponents} could be changed in runtime. For example, it is now set to compId3 and compId4. You also have to remember to rerender this control (in order to update the ids)
  • Page is rendered (from step 3). Values of compId3 and compId4 are now present (rendered) in the page.
  • On next Ajax request, components with id’s compId3 and compId4 will be rerendered.

Note: this behavior is slightly different than what you get do in RichFaces 3. In RichFaces reRender attribute when bound to an EL expression is resolved in the current request. 

It’s also possible to issue Ajax requests programmatically using the jsf.ajax.request() JavaScript API: 


   

...

   
      
      
   

A few things to look for. First, you need to include jsf.js file which provides all the JavaScript functionality. Second, for render you need to use client id (not just component id). 

Let’s look at an example using a button: 


    
    
      
    
    


Java bean:

public class Bean {
   public Date getNow () {
      return (new Date());
   }
}

In example above, we are adding Ajax behavior to standard JSF button. We specified both event and render. But, the example could also be rewritten like this: 


    
    
      
    
    


So far we covered sending an Ajax request and partial view rendering. Let’s now cover the third part: partial view processing. 

Partial view processing

In JSF 1.x (and without RichFaces) when a form was submitted, the entire form was processed on the server. Processed means that all components went through phases Apply Request Values, Process Validation and Update Model. When Ajax, there are situations when you don’t want to process all the components in the form. To control which components will get processed, we use execute attribute on f:ajax tag. 


  

In above example, when button is clicked an Ajax request is fired and the entire form will be processed on the server. 

Attribute Description
execute Determines id’s of components to be processed on server
 
Possible values for execute attribute Description
@all Process all components in view
@none Process no components
@this Process only this component, the component that triggered the Ajax request (default)
@form Process all components within this form (from which Ajax request was fired)

id’s Implicit id’s of components to be processed, space separated
EL Must resolve to Collection of Strings

More examples

Let’s look at more examples using f:ajax tag. 

If you have multiple controls that fire an Ajax request you could next f:ajax inside each one. Alternatively, you can also put f:ajax around those controls:


    
    
    
    
  
  

From example above, f:ajax will be added to each control using their default Ajax events:

h:panelGrid no default behavior, so no Ajax event will be added
h:selectBooleanCheckbox onchange
 
h:inputText onchange
 
h:commandButton onclick
 

We can also specify an event which would then be applied to children components: 


    
    
    
    
     
    
  
  

In example above, onclick event will be added to panelGrid, inputText and commandButton. commandButton would also have onfocus event applied to it. 


    
    
    
    
     
    
  

In example above we are applying the default valueChange event. It’s not possible to apply valueChange to panelGrid, so nothing will be applied to it. h:selectBooleanCheckbox and h:inputText will have valueChange applied to both. As valueChange is not a valid event for h:commanButton, the event will not be applied and h:commandButton will have only onfocus applied to it. 

Hopefully this gives you a good introduction how to use f:ajax tag in JSF 2. 

RichFaces

If you have been using RichFaces and specifically a4j:support tag then you might be wondering what’s going to happen to it? In RichFaces 4 (JSF 2 based) a4j:support is going to be renamed to a4j:ajax to match the standard tag name. a4j:ajax will use the standard f:ajax under the covers but will also provide numerous advanced features and attributes that you get today in RichFaces and which are not available in JSF 2. You will also have tags such as a4j:poll, a4j:jsFunction, a4j:outputPanel which are not available in JSF 2 and which give you more power and flexibility. 

I want to thank Nick Belaevski from RichFaces team (Exadel) for doing technical review for this article.

75 thoughts on “Learning JSF2: Ajax in JSF – using f:ajax tag

  1. Pingback: lost in thought » JSF2 Linksammlung

  2. Pingback: Learning JSF2: Ajax in JSF – using f:ajax tag | Maxa Blog « ?????????????

  3. Pingback: Random Links #173 | YASDW - yet another software developer weblog

  4. thnks for post
    i’m using MyFaces2.0.0 ans i could not find the f:ajax tag.
    whene i look at the myfaces-impl-2.0.0.jar i dont found any AjaxTag at i didn’t found
    any idea

  5. @Wuke: RichFaces doesn’t replace JSF (and won’t work without it). RichFaces is a framework that extends JSF by providing over 100 Ajax components, skins, CDK (Component Development Kit) and more.

  6. @wingyiu: it’s not possible to update content that’s not a JSF component. But, you can wrap that content in JSF panel and update it that way.

  7. @max
    Thanks for replaying.
    Is there any way to achieve a iframe-like function in JSF?
    Is jsfc attribute only available for some certain html element?

  8. Thanks for the tutorials. I have a question about bookmarkable URLs from your previous post and using Ajax from this posting. I’m finding that if I have a page that uses viewParam to load a form and use Ajax to modify the form, the page ends up failing because the viewParams are not included in the Ajax call and are then lost.

    It seems each idea works great on their own, but when combined, do not work.

    Any ideas?

  9. @max

    I just implemented this. I almost thought it worked as well, but actually this does have the same problem. Give an id to the messages tag and render that as well. The error will show up by the second time you click the button.

  10. @Brian: you’re right. I missed that part. Then you have to use ‘include view param’ tag in Faces configuration file (if you have navigation). If not, then you have add f:param (or a4j:param) to the button/link. If you use h:link or h:button, these controls come with includeViewParam attribute.

  11. Thanks for your post!
    I don’t know if this is an issue/bug, but your first example didn’t work very well in IE 9 RC. Only the first component (text) was rerendered. In other browsers – Firefox and Chrome – it worked just as expected.

  12. Thank you very much for detailed explanation of f:ajax tag.

    One big difference I see between a4j:support and f:ajax/a4j:ajax is missing action attribute. I have used a4j:support tag extensively for datatable in my app to handle “rowclick” and “rowdblclick” events. a4j:support tag’s “action” attribute generates action event which intern execute spring webflow transition. Now I don’t know how can I achieve this with missing “action” attribute in f:ajax/a4j:ajax tags. Any ideas???

    Thanks,
    Anil.

  13. Thanks for the response Max.

    Is there any other way to generate action event for “rowclick”/”rowdblclick” events on rich:datatable/rich:extendeddatatable?

    Any clues?

    Thanks,
    Anil.

  14. @Anil: you could try using a4j:jsFunction, something like this:

    rowclick=”someFunction();”

    a4j:jsFunction name=”someFunction” action=”#{bean.action}”

  15. Pingback: Delphi, Ajax and Message Broker integration with 50 lines of code | Habari! Blog

  16. @andy: I read your post on jboss.org. If you are able to transition with a4j:commandButton, then you should also be able to transition with a4j:jsFunction. What exactly didn’t work?

  17. The ajax-submit with a a4j:commandButton works perfectly but if I use a4j:jsFunction or the like spring web flow gets an ajax-request but couldn’t detect any (action)event (as I’ve seen in the log of swf) and so no transition is triggerd. So in my post you could see, how i’ve used the a4j:function.

  18. My configuration is a bit secific, because I also accept legacy jsp’s in swf and wouldn’t like to map all requests to swf, but the principle is always the same and my configuration works, only the ajax-requests that would be send by using for example a4j:function.

    so here is my configuration/code:
    (all-in-one ;-) : http://pastebin.com/embed_iframe.php?i=1aanceeS)

    pom.xml: http://pastebin.com/embed_iframe.php?i=JdErA4d4

    web.xml: http://pastebin.com/embed_iframe.php?i=5CQRGvqi

    web-application-config.xml: http://pastebin.com/embed_iframe.php?i=58UBuGAH

    webmvc-config.xml: http://pastebin.com/embed_iframe.php?i=3tuEBzEY

    webflow-config.xml: http://pastebin.com/embed_iframe.php?i=Dnpg6bcx

    MyResourceBundleMessageSource.java: http://pastebin.com/embed_iframe.php?i=MvnLVFMT

    MySessionLocaleResolver.java: http://pastebin.com/embed_iframe.php?i=Ui19kQBG

    MyResourceServlet.java: http://pastebin.com/embed_iframe.php?i=3tagXvS3

    MyWebflowExceptionHandler.java: http://pastebin.com/embed_iframe.php?i=2tSYW5D9

    test-flow.xml: http://pastebin.com/embed_iframe.php?i=Cr2vjQa7

    Test.xhtml: http://pastebin.com/embed_iframe.php?i=1LB6rQw8

  19. @andy: I reviewed test.xhtml, and there are a number of things:

    – a4j:jsFunction shouldn’t be nested inside another component (also, don’t nest more than one a4j:ajax or similar Ajax component)

    – There is not ajaxingle in RichFaces 4. The attribute is called ajaxSingle and is only available in RichFaces 4. This is not a real problem at the attribute is just ingored.

    – You have execute=”someFunction”, execute attribute should point to input components to be executed on the server, not another component.

    – action=”AJAX_TEST” – this implies you have a navigation rules called AJAX_TEST.

    – Here is how to use a4j:jsFunction: http://mkblog.exadel.com/2010/06/using-richfaces-a4jjsfunction-sending-an-ajax-request-from-any-javascript/

    Hope this helps…

  20. Thanks for your reply, i’ve recognize:
    – a4j:jsFunction shouldn’t be nested inside another component (also, don’t nest more than one a4j:ajax or similar Ajax component)
    – There is not ajaxingle in RichFaces 4. The attribute is called ajaxSingle and is only available in RichFaces 4. This is not a real problem at the attribute is just ingored.
    So I’ve moved the a4j:jsFunction-Tags between the h:form-tag and the h:body-tag and renamed the attribut ajaxSingle.

    But if you’r right with:
    – You have execute=”someFunction”, execute attribute should point to input components to be executed on the server, not another component.
    – action=”AJAX_TEST” – this implies you have a navigation rules called AJAX_TEST.

    How could I trigger a transition in spring web flow, if the user selects an item in the selectOneMenu? It’s always the same problem, because swf get’s an ajax-request but couldn’t detect an (action)event to trigger the corresponding transition!

  21. @andy: sorry, I made a typo, ajaxSingle is only in RichFaces 3. You don’t need in RichFaces 4.

    You can try something like this:

    
    ...
    
    
    
    
  22. Thanks for this suggestion.

    So if I use as follows:
    h:panelGroup>
    h:selectOneMenu id=”test” value=”#{flowScope.testBean}” converter=”#{ObjectConverter}” styleClass=”string_20″ onchange=”someFunction()”>
    f:selectItems value=”#{flowScope.testVec}” var=”test” itemLabel=”#{test.description}” />
    /h:selectOneMenu>
    /h:panelGroup>

    a4j:jsFunction id=”someFunction” name=”someFunction” action=”AJAX_TEST” render=”…” />

    I get an ajax-request and swf could detect an action event “AJAX_TEST” and the corresponding transition will be triggert.
    BUT: the value-binding in selectOneMenu for the testBean in the flowScope is now not working! So if I get the request in cause of a new selected item in the selectOneMenu, I always get the first selected item and the value of the testBean will never changed! :-o Also the a4j:status-Tag doesn’t show, that an ajax-request is send!
    So is it so complex to get the same behavior as the a4j:support-Tags in RF 3 does???

  23. @andy: how did you define a4j:status? If you send an Ajax request, then a4j:status show show. As for the value not being set into the bean property, I’m not sure. It’s a pretty simple case so it should work. Does the value get set if you don’t use Ajax?

  24. I simply add the a4j:status-tag to the page and it works for a4j:ajax, but not for the elaborated case. If i set the status-attribute in the used tags it also doesn’t work. If I use a simple command-Button to submit the selected value in the drop-down-box it also doesn’t work. But if I use RF 3.3 and the a4j:support-tag it works fine, so I doesn’t understand, why a simple case like this doesn’t work for RF 4!?

  25. @andy: just to confirm, when you use the button to submit, it still doesn’t work? If that’s the case, then I would figure out why it doesn’t work first. It could be a JSF2 issue with Spring. When the standard button is used, you are using JSF2, not RichFaces.

  26. I’m sorry, cause I test it again with a simple commandButton and it works. I just have triggered a wrong transition. So:
    – If I use only JSF2 and SWF: IT WORKS
    – If I use JSF2 and the SWF-tag sf:ajaxEvent event=”onchange” action=”AJAX_TEST” around the selectOneMenu-tag: IT WORKS, but the swf-tags are incompatible with the rf-tags, so no a4j:status works, …so I’d like to use only rf-tags
    – If I use RF 3.3 and the a4j:ajax-tag: IT WORKS
    – If I use the a4j:jsFunction-tag and the onchange-Attribute: I get an ajax-request and swf could detect an action event “AJAX_TEST” and the corresponding transition will be triggert. BUT: the value-binding in selectOneMenu for the testBean in the flowScope is now not working! So if I get the request in cause of a new selected item in the selectOneMenu, I always get the first selected item and the value of the testBean will never changed! :-o Also the a4j:status-Tag doesn’t show, that an ajax-request is send!
    So I thinking: My configuration is correct, because JSF works, SWF works, Spring Faces works, and RF 3.3 works. But if I use RF 4, I need an alternative for the a4j:ajax-tag that works and emulate the same behaviour.

  27. sorry, I mean
    “If I use RF 3.3 and the a4j:support-tag: IT WORKS”
    and
    “I need an alternative for the a4j:support-tag that works and emulate the same behaviour”
    ofcourse! ;-)

  28. so now I’m confused:
    I use the a4j:ajax-tag and the a4j:jsfunction-tag:
    h:selectOneMenu id=”selectDepartment” value=”#{flowScope.testBean}” converter=”#{ObjectConverter}” styleClass=”string_20″ onchange=”sendAJAX_TEST()”>
    f:selectItems value=”#{flowScope.testVec}” var=”selTest” itemLabel=”#{selTest.description}” />
    a4j:ajax event=”change” render=”showTest” />
    /h:selectOneMenu>

    a4j:jsFunction name=”sendAJAX_TEST” action=”AJAX_TEST” />

    and now I get TWO ajax-requests!?! the first request is called by the a4j:jsFunction and executes the corresponding swf-transition and the second request is called by the a4j:ajax-tag, which binds the values! But it’s the wrong order, because the business logic is called with the wrong/old values, and than the values are changed to that the user entered. So it’s not the correct solution and also 2 ajax-requests are not with good performance!

  29. @andy: you get two Ajax requests because you send two Ajax requests. One is from a4j:jsFunction and the other via a4j:ajax. Only one should be used. I’m guessing the form is submitted fine using a4j:jsFunction and there is probably something else that happens and the new value doesn’t get set.

  30. but it’s just defined:
    if you look at the migration guide (http://community.jboss.org/wiki/RichFacesMigrationGuide33x-4xMigration-ComponentsMigration-A4jComponents): a4j:ajax is corresponding to a4j:support!
    and the a4j:jsFunction is just for requesting new data:
    The component performs Ajax requests directly from JavaScript code and retrieves server-side data. The server-side data is returned in JavaScript Object Notation (JSON) format prior to the execution of any JavaScript code defined using the oncomplete attribute.
    If you’d like to submit something, you must use a4j:param-Tags for the a4j:jsFunction. But it’s not comfortable!!!

    So now, it’s the same Problem: What’s the alternative for the a4j:support-tag? or: how an action-Attribute could be added to an a4j:ajax-Tag?

  31. if I use

    a4j:ajax event=”change” render=”showTest” oncomplete=”sendAJAX_TEST()” />

    andy

    a4j:jsFunction name=”sendAJAX_TEST” action=”AJAX_TEST” render=”showTest” />

    it works, but with TWO ajax-Requests, which aren’t with performance!

  32. @andy: a4j:jsFunctions sends the same request as a4j:ajax but from a JavaScript function: “The component performs Ajax requests directly from JavaScript code..”. This post describes how a4j:jsFunction works: http://goo.gl/RKBLM

  33. Thanks! I’ve read the link and test it in my application, but it doesn’t work! So I’ve checked out the webflow-richfaces-showcase-project from the spring-svn (https://src.springframework.org/svn/spring-samples) and adapt it to RF4 and SWF 2.3.0. Than I’ve modified step1 in “Popup With State Transition” to test the case shown in your link (http://goo.gl/RKBLM) but it doesn’t work! Here is the modified project, so you can download it on: http://www.file-upload.net/download-3490981/webflow-richfaces-showcase.rar.html
    So is it a RF4-bug?

  34. @andy: I don’t know whether it’s a bug in RichFaces or maybe Spring. Just trying probably won’t tell you where the bug is, this may require real debugging. However, you can try and narrow down the issue.

    – Does it work with just h:commandButton (no Ajax)?
    – Does it work with h:commandButton and f:ajax?
    – Does it work with a4j:commandButton?
    – Does it work with a4j:jsFunction?

  35. Congratulations for the post!
    I have a doubt about the client update mechanism, when using the render attribute, it renders all the markup, but in most of cases the markup is not modified, but tha value has changed.
    How can I change ONLY the value of some components after an ajax call?

    Thanks
    david

  36. @max, for example in the code below as you are writing on the inputText the backing bean changes the “text” property and render the whole outputText component, with all the HTML markup (for example etc etc)
    But what you need is only the value, not the entire markup, so you could get the new value for the text comnponent and perform a text.setAttribute (“value”, text_new_value).

    Imagine an scenario where the component to update is a comboBox with 100 elements and after an ajax call we want to update its VALUE. Using the “render” attribute we’ll force to receive the 100 elements and rerender them, right?
    And we just need the new value.

    I hope this clarify my question

  37. @David: You can do it with directly with JavaScript API. For example, call a JavaScript function in oncomplete callback to change only the value.

  38. @max: Thank you max,
    This is how I’m doing it right now, but I wondered if there were another (automated) way of doing it.
    Thanks againg and best regards
    david

  39. Pingback: Trabalhando com JSF 2 – O que há de novo e Ajax « Michel Souza

  40. Pingback: Confluence: NG Leverandørportalen

  41. Pingback: Confluence: NG Leverandørportalen

  42. I follow your examples and make this script and didn’t work, can you help me what’s wrong? Thanks for all

    public class Bean2 {
    public String valor1;

    public Bean2() {
    }

    public String getValor1() {
    return valor1;
    }

    public void setValor1(String valor1) {
    this.valor1 = valor1;
    }
    }

  43. @Jorge: what exactly didn’t work? Did you see any error messages? Did you use just JSF 2 or also RichFaces 4? Please link the page code via pastie.org.

  44. I follow your examples and make this script and didn’t work, can you help me what’s wrong? Thanks for all

    h:form>
    h:panelGrid columns=”1″>
    h:inputText value=”#{bean2.valor1}”/>
    h:commandButton value=”Type text” >
    f:ajax render=”texto2″/>
    /h:commandButton>
    h:outputText id=”texto2″ value=”#{bean2.valor1}” />
    /h:panelGrid>
    /h:form>



    public class Bean2 {
    public String valor1;

    public Bean2() {
    }

    public String getValor1() {
    return valor1;
    }

    public void setValor1(String valor1) {
    this.valor1 = valor1;
    }
    }

  45. Pingback: Learning JSF2: Ajax in JSF – using f:ajax tag | Lorelei Blog

  46. Pingback: render / update attribute values jsf / primefaces « [ chawi3 ]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s