Often, we notify user content is download-in-progress by using loading GIFs, which in background are displayed / hidden by using classical callbacks that jQuery ajax exposes namely beforeSend and success, error. One of the disadvantages of using GIF loader is that it cannot indicate by any means, what is the current status of the background process towards completion. However, XMLHttpRequest object exposes an event progress which is triggered after every chuck of data recieved. The event Object that is passed has LengthComputable property which indiactes if the server has let knew the client the total size of data to be downloaded and the current chunk number.
jQuery doesnot allow any api of this nature, however we can extend the xhr option to a custom function that create and retuns a new XMLHttpRequest object, to which we can attach event listener for progress event.
I have used bootstrap Progress-Bar to show progess graphically. here is a piece of code.
$.ajax({ url:"", async: true, xhr: function () { var xhr = new window.XMLHttpRequest(); //Upload Progress xhr.upload.addEventListener("progress", function (evt) { if (evt.lengthComputable) { var percentComplete = (evt.loaded / evt.total) * 100; $('div.progress > div.progress-bar').css({ "width": percentComplete + "%" }); } }, false); //Download progress xhr.addEventListener("progress", function (evt) { if (evt.lengthComputable) { var percentComplete = (evt.loaded / evt.total) *100; $("div.progress > div.progress-bar").css({ "width": percentComplete + "%" }); } }, false); return xhr; },
Bootstrap Html
<div class="progress"> <div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;"></div> </div>