Search code examples
ajaxjsfjsf-2progress-barloading

Show loading progress when making JSF Ajax request


How can I show some loading message when making request using <f:ajax>?


Solution

  • If you're not already using a 3rd party component library which could already have a ready-made component for that, such as PrimeFaces with <p:ajaxStatus>, then you can use the JSF-provided JavaScript faces.ajax.addOnEvent() function (and eventually also faces.ajax.addOnError()) to hook a function on ajax events.

    Here's a basic kickoff example:

    <script>
        faces.ajax.addOnEvent(function(data) {
            var ajaxstatus = data.status; // Can be "begin", "complete" and "success"
            var ajaxloader = document.getElementById("ajaxloader");
    
            switch (ajaxstatus) {
                case "begin": // This is called right before ajax request is been sent.
                    ajaxloader.style.display = 'block';
                    break;
        
                case "complete": // This is called right after ajax response is received.
                    ajaxloader.style.display = 'none';
                    break;
        
                case "success": // This is called when ajax response is successfully processed.
                    // NOOP.
                    break;
            }
        });
    </script>
    
    <img id="ajaxloader" src="ajaxloader.gif" style="display: none;" />
    

    See also section 13.3.5.2 of the Jakarta Faces 4.0 specification:

    13.3.5.2 Monitoring Events For All Ajax Requests

    The JavaScript API provides the faces.ajax.addOnEvent function that can be used to register a JavaScript function that will be notified when any Ajax request/response event occurs. Refer to Section 14.4 “Registering Callback Functions” for more details. The faces.ajax.addOnEvent function accepts a JavaScript function argument that will be notified when events occur during any Ajax request/response event cycle. The implementation must ensure the JavaScript function that is registered must be called in accordance with the events outlined in Section TABLE 14-3 “Events”.

    Note: in case you're still using JSF 3.0 or older, then use jsf.ajax namespace instead of faces.ajax as in jsf.ajax.addOnEvent(...).