Basit
Basit

Reputation: 8626

How to load images using ajax when page loads

I have a JSF page on which i have 8 images like.

*For jquery viewer Only: Please donot confuse with the JSf syntax. Behind the scenes it's all converted to plain HTML. Like h:panelGrid convert into table element. p:graphicImage convert into img element.Actually i want to know the logic to load images using jQuery ajax. Like using jQuery i call the server, then get the images from database and when images load completely on the path, then i change the img src attribute to change the default image with the loaded one. When page loads the on the default path there is a default image like /resources/images/no-preview.jpg. So i want that when images loaded then i replace it with like /resources/images/Image1.jpg, /resources/images/Image2.jpg and so on *.

<h:panelGrid columns="5" width="10%" style="position: relative; top: 50px; "
             columnClasses="asteriskColumns, nameColumns" >

    <h:outputText value="*" />
    <h:outputText value="Map: " />
    <p:fileUpload id="cityMap" widgetVar="uploader" description="Image"
                  update="city" allowTypes="*.jpg;*.png;*.gif;*.jpeg;"
                  auto="true" fileUploadListener="#{cityDetail.imageUpload}"
                  style="position: relative;"  >

    </p:fileUpload>

    <p:graphicImage id="city" value="#{cityDetail.imagePath}" width="80"
                    height="50" cache="false" style="position: relative;">

        <f:event type="preRenderComponent" listener="#{cityDetail.putImage}" />

    </p:graphicImage>

    <h:commandLink value="remove" title="Remove Picture"
                   style="color: #0d5b7f;text-decoration: underline;"
                   onclick="if (! confirm('Are you sure, you want to remove picture?') ) { return false;}; return true; ">

        <f:ajax event="click" render="city" listener="#{cityDetail.removeImage}"/>

    </h:commandLink>
    .....
    7 more images in same format

</h:panelGrid>

In the constructor i am suing something like this to get images from database

public class CountryPages_Detail {
    private String imagePath = "/resources/images/no-preview.jpg";
    String path = externalContext.getRealPath("/resources/images") + "/" ;
    public CountryPages_Detail() {
        ....
        String cityMapQuery = "SELECT citymap From city Where cityid='" + cityID + "'";
        String countryMapFileName = "countryMap_" + saarcCountryId;
        // 7 more queries in same format

         ArrayList countryMapQueryArray = addCredentialsToList(externalContext, countryMapQuery, countryMapFileName, response);
         //7 more

         ArrayList mainArray = new ArrayList();
         mainArray.add(countryMapQueryArray);
         ...
         ArrayList result = ConnectionUtil.showImagesFormDatabase(mainArray);
    } //end of constructor     
} //end of class CountryPages_Detail

public static ArrayList showImagesFormDatabase(ArrayList list) {
    for (int i = 0; i < list.size(); i++) {
        ArrayList fileCredentialsList = ((ArrayList) list.get(i));
        String query = fileCredentialsList.get(0).toString();
        sqlStatement = conn.createStatement();
        resultSet = sqlStatement.executeQuery(query);
        if (resultSet != null) {
            while (resultSet.next()) {
                imageBytes = resultSet.getBytes(1);
                setResponceForDatabaseImages(fileCredentialsList);
                imageName = createFile(fileCredentialsList, imageBytes);
                if (imageName != null) {
                    imageNameList.add(imageName);
                }
            } //end of while()
        } //end of if()
    } //end of for()

    return imageNameList;

} //end of showImagesFormDatabase()

As you can see i get images from database when page loads. Get the images bytes from database, then create imagefile on the path from that bytes. But i have 8 images. If any of the image size is large then i have to wait which is frustrating.

I want that when page loads, then instead of laoding images from database i use ajax. Means my rest of the page get loads and images get load from behind the scenes and when all images get load then the images shown in the p:graphicImage. While image is loading then the loading icon should be displaying in the p:grahicImage and when image loads completely then icon gone and image should be shown.

How can i do it?

Thanks

Edit: ------------------------------------------------------------------------------------

 <ui:define name="content">
     <h:form id="faqAddUpdateForm" prependId="false">
         <h:panelGrid columns="5" width="10%" style="position: relative; top: 50px; "
             columnClasses="asteriskColumns, nameColumns" >
         ....
         </h:panelGrid>
     </h:form>

     <h:form id="hidden" style="display:none">
                <h:commandLink id="link">
                    <f:ajax event="click" listener="#{countryPages_Detail.loadImagesUsingAjax}" />
                </h:commandLink>
     </h:form>

     <script>
         window.onload = function() {
             document.getElementById('hidden:link').onclick();
          }
      </script>
 </ui:define>

Upvotes: 0

Views: 3248

Answers (1)

Matt Handy
Matt Handy

Reputation: 30025

You could load the images, when document is ready. However, the h:body onload does not work (as reported in BalusC's answer here).

The referenced answer will give you a way to get it working. You need to trigger a hidden commandLink that has an ajax listener attached. The listener should call the method that produces the images and the ajax call should update the component containing the images.

To partially update your page on an ajax call, use the render attribute of f:ajax:

<h:commandLink id="link">
   <f:ajax event="click" 
           render=":faqAddUpdateForm"
           listener="#{countryPages_Detail.loadImagesUsingAjax}" />
</h:commandLink>

render=":faqAddUpdateForm" will render the whole form. If that is too much, give your panelGroup that contains the images an id (e.g. "imageGroup") and use this id in the render attribute:

render=":faqAddUpdateForm:imageGroup"

Upvotes: 0

Related Questions