18

I want to show the user percentage of the ajax response loaded with a progressbar. Is there a way to achieve it? Right now I am showing just an image.

Here is my code sample :

$('#loadingDiv').show();

$.ajax({
        type : 'Get',
        url : myUrl,
        success : function(response) {
            $('#loadingDiv').hide();
            populateData(response);
        },
        error: function(x, e) {
                    $('#loadingDiv').hide();
            if (x.status == 500 || x.status == 404) {
                    alert("no data found");
                }
        }
    });

HTML code:

<div id="loadingDiv">
     <img src="loading-img.png"/>
</div>
Premshankar Tiwari
  • 3,006
  • 3
  • 24
  • 30
  • 2
    A bit of [research](http://stackoverflow.com/questions/10559264/possible-to-calculate-how-much-data-been-loaded-with-ajax) – Patsy Issa May 22 '13 at 11:42

1 Answers1

46

There are two ways to show real percentage. Briefly...

One - old school native JavaScript or jQuery ajax, for which you need server support as well, a different URL which can give you updates. And you keep hitting that URL on an interval.

Two - modern native native JavaScript in HTML5 browsers, supporting XMLHTTPRequest2, also known as AJAX 2, defined by new Web and HTML5 Standards.

If two, welcome to the new web!!
Multiple features have been added to Browsers that enhance connectivity - part of HTML5 features.

XMLHTTPRequest2 enables events in AJAX that help monitoring progress, as well as a lot of other things, from JavaScript itself. You can show the real percentage by monitoring the actual progress:

var oReq = new XMLHttpRequest();

oReq.addEventListener("progress", updateProgress, false);
oReq.addEventListener("load", transferComplete, false);
oReq.addEventListener("error", transferFailed, false);
oReq.addEventListener("abort", transferCanceled, false);

oReq.open();

Then you can define the handlers attached above (progress in your case):

function updateProgress (oEvent) {
  if (oEvent.lengthComputable) {
    var percentComplete = oEvent.loaded / oEvent.total;
    // ...
  } else {
    // Unable to compute progress information since the total size is unknown
  }
}

jQuery can be used in the second case as well. After all, jQuery is for helping you with less code, more doing!

Hoping that you are focusing on HTML5 and the new web solution, I would point you to Mozilla DOC - Monitoring Progress in AJAX from where I have taken this solution.

Every Browser now has a documentation for the web (like the one above from Mozilla) and additionally, all of them are contributing to a common venture called Web Platform, together with other influential Web and Internet giants - for a common updated Web Documentation. It is a work in progress, so not complete.

Also, there is no native functionality in the old AJAX, to monitor progress.

In the old-school way, you would have to create an interval function that would keep on hitting a separate URL to get the progress update. Your server also has to update the progress and send that as a response from that URL available from a different port.

Om Shankar
  • 7,989
  • 4
  • 34
  • 54
  • Had no idea about `XMLHTTPRequest2`, amazing. – NiCk Newman Oct 27 '15 at 00:42
  • This can't work for me because I have a very small file to retrieve (just a few BYTES); but my script takes quite a long to be executed; I guess it's due to server delay... but how can I distinguish a stuck script from a slow server? I print a "please wait..." message before starting retrieval, but a "please wait" message for a 10 bytes output can't last more than 10 seconds without raising suspect of "something locked up" in the user. See http://stackoverflow.com/questions/35482101/how-to-use-jquery-to-use-online-translation-apis/35485375#35485375 – jumpjack Feb 19 '16 at 09:48
  • It is fine for javascript, but how can I use it in jQuery? – Merbin Jo Mar 29 '17 at 06:23
  • The "progress" only give status when posting data. Example, upload a large file under a blob this will be very helpful. I'm also looking for a solution to count while server processing and special while downloading. But it seems impossible – Nguyen Tu Mar 22 '19 at 12:35
  • The answer is great, I just wanna add another documentation about XMLHttpRequest's progress_event: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/progress_event. It also has a live example! – code đờ Jun 03 '21 at 07:24