I am trying to capture ajax request`s progress. I am following article from this link http://www.dave-bond.com/blog/2010/01/JQuery-ajax-progress-HMTL5/.
It is not working as expected. Div with id progressCounter should have something in it with % as far as i understand it but nothing happens in my case. Any Help ?
It seems to me like if (evt.lengthComputable) {
is not working in XHR
JSFIDDLE: http://jsfiddle.net/bababalcksheep/r86gM/
HTML:
<div id="progressCounter"></div><br> <div id="loading">Loading</div><br> <div id="data"></div>
JS:
var progressElem = $('#progressCounter'); var URL = "https://api.github.com/users/mralexgray/repos"; $("#loading").hide(); // write something in #progressCounter , later will be changed to percentage progressElem.text(URL); $.ajax({ type: 'GET', dataType: 'json', url: URL, cache: false, error: function (xhr, ajaxOptions, thrownError) { alert(xhr.responseText); alert(thrownError); }, xhr: function () { var xhr = new window.XMLHttpRequest(); //Download progress xhr.addEventListener("progress", function (evt) { if (evt.lengthComputable) { var percentComplete = evt.loaded / evt.total; progressElem.html(Math.round(percentComplete * 100) + "%"); } }, false); return xhr; }, beforeSend: function () { $('#loading').show(); }, complete: function () { $("#loading").hide(); }, success: function (json) { $("#data").html("data receieved"); } });
Use the ajaxStart to start your progress bar code. $(document). ajaxStop(function(){ // hide the progress bar $("#progressDialog"). modal('hide'); });
Ajax technique in the nutshell leverages the XHR request to send and receive data from the webserver. This object is provided by the browser's javascript environment. It transfers the data between the web browser and server.
The ProgressEvent.lengthComputable read-only property is a Boolean flag indicating if the resource concerned by the ProgressEvent has a length that can be calculated. If not, the ProgressEvent.total property has no significant value.
So in your case if you debug a little , you will find evt.lengthComputable = false;
so you can not trace the progress;
xhr.addEventListener("progress", function (evt) { console.log(evt.lengthComputable); // false if (evt.lengthComputable) { var percentComplete = evt.loaded / evt.total; progressElem.html(Math.round(percentComplete * 100) + "%"); } }, false);
If lengthComputable
is false within the XMLHttpRequestProgressEvent
, that means the server never sent a Content-Length header
in the response.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With