Search code examples
ajaxjsfjsf-2primefacesspring-webflow

Fetch data with Ajax to Datatable after page render


It is simple idea to resolve, however I've never done it before and need an advice. I use Spring, Spring Webflow and JSF with Primefaces.

I use external webservices to fetch some data in table. Sometimes it is working slower than the website call and I want to avoid 'waiting' for load. My idea (it is nothing new) is to load the page with all the static (or local-server) content and then call for the external webservice to fetch the data. Than display it when it's finished.

So far it looks like this:

website:

<p:dataTable id="table" var="item" value="#{lastfm.topArtists}">
                    <p:column headerText="Model" sortBy="#{item.name}">
                        <h:outputText value="#{item.name}" />
                    </p:column>
</p:dataTable>

and the Bean itself its just:

private List<Artist> topArtists = new ArrayList<Artist>();
public void init(String u) {
    topArtists = (List<Artist>) User.getTopArtists(u, StaticContent.api_key);
}

User - is the Webservice API.

ATM init loads on-render of the website but I want to avoid it, call it in some way after page load, and display on success.

I assume it could be some javascript function with jquery, using onDocumentReady() and onSuccess for ajax, but I really have no idea how to connect it.

Thanks!


Solution

  • Polling component of prime faces might help you achieve this.

    http://www.primefaces.org/showcase-labs/ui/poll.jsf

    <h:form id="form">  
    <p:poll interval="3"   
            listener="#{lastfm.topArtistsRetrieved}" update="table" />  
    
    <p:dataTable id="table" var="item" value="#{lastfm.topArtists}">
                    <p:column headerText="Model" sortBy="#{item.name}">
                        <h:outputText value="#{item.name}" />
                    </p:column>
    </p:dataTable>
    </h:form>
    

    I assume that User.getTopArists will inform you when it is finished. Basically you need a flag which indicates whether your process is ended or not. And through prime faces polling you should check whether the flag is raised or not and through ajax update you should print the results when they are ready. You might even show the progress of the process through this flow.