How to show loading status in percentage for ajax response?

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 DOCMonitoring 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.

Leave a Comment