12 Replies Latest reply on Dec 5, 2007 5:58 AM by Florian Marwede

    Efficient ajax howto

    Mikael Andersson Master

      Hi

      I am looking for advice on how to make the ajax requests as efficient as possible.

      For instance when using a4j:poll who can I limit the amount of data sent back from the server to its bare minimum?

      a4j:region doesn't affect the returned content does it, but affects which things are updated on the page right?

      Many thanks,
      Mike

        • 1. Re: Efficient ajax howto
          Mikael Andersson Master

          Sorry probably the wrong forum :), will post this on the ajax4jsf users form instead.

          • 2. Re: Efficient ajax howto
            Lotfi Mellouk Master

             

            "mail.micke@gmail.com" wrote:
            Sorry probably the wrong forum :), will post this on the ajax4jsf users form instead.


            it's the right forum, rich faces and ajax4jsf was merged since the 3.1.0 version.

            • 3. Re: Efficient ajax howto
              Mikael Andersson Master

              Thanks,
              just managed to figure that one out myself little while ago looking through the ajax4jsf forum :)

              Question:
              Any experience out there with using jsFuction and JSON for efficient ajax updates?
              Is it possible for instance to output a JSON response in a action method and call responseComplete() to avoid rendering the page? And then just grabbing the JSON data object and update the relevant bits.

              Sorry if these are super simple questions.

              Many thanks,
              Mike

              • 4. Re: Efficient ajax howto
                Florian Marwede Expert

                Hi, I don't think these are simple questions :-)

                Our current project is to migrate a rich client for broadcast management (for radio/tv stations) from Java Swing to a complete stand alone web client.

                And here we use jsFunction and JSON in many cases. An example use case:

                A user want to create device in a circuit diagram.

                1.) He drags and drops it from the toolbox in our embedded Javascript(!) graphical editor. But first only a "please wait"-ModalPanel is shown.

                2.) With JSFunction we come to the SessionBean and from there to the DB to fetch some Data for drawing the device in the Editor.

                3.) When the answer comes back, we asked the user with a modal panel to give a name to the device.

                4.) After he clicks OK, the model panel disappears (and the please wait model panel shows up again) and another JSFunction call goes over the SessionBean to the DB to create the device data there.

                5.) When the answer comes back, a JSON-String is created with all data for drawing the device (for example the given name) and the Editor is advised to draw it (and the please wait modal panel disappears again).

                I'm not allowed to give the complete code to public, but if it helps you, I can answer concrete questions to these topics.
                Perhaps I can provide code snippets where you see the abstract idea how it works. But to make it clear: I'm not in expert but a beginner concerning these topics, too.

                • 5. Re: Efficient ajax howto
                  Mikael Andersson Master

                  Hi fmarwede

                  Thanks for taking the time to help out.

                  Currently I'm mainly interested in how to reduce the amount of date sent from the server when there is an ajax request.

                  Perhaps you could give a simple example of the XHTML code to initialize a request and update the page content using jsFunction and JSON. Toghether with some simple action method that produces some JSON data for the page.

                  To me it seems that usually quite a lot of data comes back in the response even if only a small part of the page needs updating. It would be really nice to have a simple way of just sending back some JSON data, lean and mean.

                  Many thanks,
                  Mike

                  • 6. Re: Efficient ajax howto
                    Florian Marwede Expert

                    Hi Mike,

                    I'll try that. Look at 4.) of my "createDevice"-example. Let's take a look at the jsFunction-Tag:

                    <a4j:jsFunction name="executeObjectCreation"
                     action="#{ctrl.executeCommand}"
                     data="#{ctrl.dataModel.currentExecutionResult}"
                     oncomplete="drawCreatedObject(data);" >
                     <a4j:actionparam name="Param1" assignTo="#{ctrl.someData}"/>
                     <a4j:actionparam name="Param2" assignTo="#{ctrl.dataMap['somekey']}"/>
                    </a4j:jsFunction>
                    


                    Now we can use the Javascript function executeObjectCreation with two parameters. The following will happen in this order (of course there is no necessity to use always all of them):

                    1.) The two parameters will be set in the places specified with Expression language. (put here the input for your logic)
                    2.) The action is called (put your logic here)
                    3.) The get-Method specified with data-Attribute is called (get the result of your logic)
                    4.) The Javascript Method specified with oncomplete-Attribute is called (with the parameter returned by Method of 3.) . This is the JSON-String!!

                    Let's have a look at the JSON-Export which is realized with the strategy pattern (see GoF). We have several data classes and for each data class a JSON exporter class, which knows what data of the data class we need directly in Javascript. A central JSONExporter provides a service method, where you can put a any dataclass and per reflection the concerning exporter class is called.
                    Here an example for such an exporter class:

                    import org.richfaces.json.JSONException;
                    import org.richfaces.json.JSONObject;
                    
                    public class SomeDataToJSON implements DataToJSON
                    {
                    
                     public String toJSON(Object obj)
                     {
                     SomeData data = (SomeData) obj;
                     JSONObject dataToJSON = new JSONObject();
                     try
                     {
                     dataToJSON.put("ID", data.getObjPhysName());
                    
                     dataToJSON.put("name", data.getName());
                    
                     dataToJSON.put("width", data.getWidth());
                     dataToJSON.put("height", data.getHeight());
                     }
                     catch (JSONException e)
                     {
                     //TODO Approriate exception handling
                     e.printStackTrace();
                     }
                     return dataToJSON.toString();
                     }
                    
                    }
                    


                    As you can see, the SimpleJSON library build the JSON-String for you (integrated in Richfaces). On the basis of my experience I can say that this library does not all for you. Sometimes you have to add some brackets or something else.

                    Here your Javascript code

                    var jsonString = executeObjectCreation("test", "anotherParam");
                    var myObject = eval(jsonString);
                    
                    var name = myObject.name;
                    ...
                    


                    All that works and is (relatively) well understood. The difficult part of your question is: How to update your page with this information. As I said, we update our JavaScript editor with that. How to update a bundle of richfaces components...until now we haven't done that yet.

                    Although I hope it helps!

                    Florian

                    • 7. Re: Efficient ajax howto
                      Florian Marwede Expert

                      Let me add: As Ilya and Sergej often repeat, use ajaxSingle, eventQueue, ignoreDuResponses and so on to control and reduce your traffic.

                      • 8. Re: Efficient ajax howto
                        Mikael Andersson Master

                        Many thanks for the detailed post.

                        I will give try this stuff right away and see if I can get something simple work.

                        Will be interesting to see with firebug exactly what is sent back from the server :)

                        • 9. Re: Efficient ajax howto
                          Mikael Andersson Master

                          Got it working

                          From what I can tell by looking at the response in FireBug it does seem like only the relevant data is sent (except for a lot stylesheet and js scripts).

                          Firebug gives some confusing output though.
                          The reported response content length is 3.5Kb , but it says that the request took 53Kb ?
                          I'm viewing "ALL" under the Net tab, and I can not see any style sheets or script files being fetched.
                          Anyone know what these figures mean?

                          It would be great if one of the framework developers could give a quick explenation about differences in request processing when using jsFunction (if there is any).
                          Would be nice to be able to explain this in some detail to co-workers who are curious.

                          One quick not for others who don't have much JSON experience (like myself), you have to modify the "eval" line a bit to something like this

                          var myObj = eval("(" +data +")" );
                          


                          Note the added parens.

                          Many thanks for the help and if there are more tips/hints/suggestions they are very welcome.

                          Mike



                          • 10. Re: Efficient ajax howto
                            Florian Marwede Expert

                            Great! Thank you for analyzing with FireBug, we haven't done that yet.

                            By the way I'm very interested in any comment concerning these technique and my proposed use of it...

                            • 11. Re: Efficient ajax howto
                              Mikael Andersson Master

                              I started a wiki page in the RichFacesCookbook.

                              http://labs.jboss.com/wiki/en//RichFacesCookbook/JsFunctionJson

                              Please feel free to update it with more information.

                              Cheers,
                              Mike

                              • 12. Re: Efficient ajax howto
                                Florian Marwede Expert

                                Hi Mike,

                                it looks good at first glance. I'll update it when I find out more about that.

                                Perhaps you didn't notice: unfortunately I found a bug concerning the javascript event handlers used in context with jsFunction:

                                http://jira.jboss.com/jira/browse/RF-1487

                                Please vote for it!

                                @Ilya (or other staff member): Do the developers pay attention to the votes? Or don't you use this jira feature?