Skip to content Skip to sidebar Skip to footer

Setting Up Ajax Progress Bar

Ok im new to AJAX. Kind of know about the lifecycle of a request, IE uses ActiveXObject stuff like that. However now im faced with a real world problem. I have a servlet running in

Solution 1:

Basically, you'd like to store a reference to the task and inherently also its progress in the HTTP session (or in the Servlet context if it concerns an application wide task). This way you must be able to retrieve information about it on every HTTP request.

In JavaScript, you can use setTimeout() or setInterval() to execute a function after a certain timeout or at certain intervals. You can use this to repeatedly fire Ajax requests to request current status of the progress. Once the status is retrieved, e.g. in flavor of an integer with a max value of 100 (the percentage), just update some div representing a progressbar and/or the percentage text accordingly in the HTML DOM tree.

jQuery is very helpful in firing ajaxical requests and traversing/manipulating the HTML DOM tree like that. It minimizes the code verbosity and crossbrowser compatibility headaches.

Imagine that the doGet() of the servlet look like this:

protectedvoiddoGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
    StringprocessId="longProcess_" + request.getParameter("processId");
    LongProcesslongProcess= (LongProcess) request.getSession().getAttribute(processId);
    intprogress= longProcess.getProgress();

    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(String.valueOf(progress));
}

Then you can use it like follows:

functioncheckProgress() {
    $.getJSON('progressServlet?processId=someid', function(progress) {
        $('#progress').text(progress + "%");
        $('#progress .bar').width(progress);

        if (parseInt(progress) < 100) {
            setTimeout(checkProgress, 1000); // Checks again after one second.
        }
    });
}

Post a Comment for "Setting Up Ajax Progress Bar"