Reputation: 441
$.ajax({
url: 'https://www.udacity.com/public-api/v0/courses',
xhr: function () {
console.log('xhr');
var xhr = new XMLHttpRequest();
xhr.addEventListener('loadend', uploadComplete, false);
function uploadComplete(event) {
console.log('uploadComplete');
}
xhr.addEventListener("progress", function (evt) {
console.log(evt.percentComplete);
console.log([evt.lengthComputable, evt.loaded, evt.total]);
// if (evt.lengthComputable) {
var percentComplete = (evt.loaded / evt.total) * 100;
console.log(percentComplete + "p")
//}
}, false);
return xhr;
},
success: function (response) {
console.log("success")
}
});
For the above code, the output I'm getting in console is as below:
script.js:15 [false, 22463, 0]
script.js:18 Infinityp
script.js:14 undefined
script.js:15 [false, 53062, 0]
script.js:18 Infinityp
script.js:14 undefined
script.js:15 [false, 85830, 0]
script.js:18 Infinityp
script.js:14 undefined
script.js:15 [false, 124733, 0]
script.js:18 Infinityp
script.js:14 undefined
......
Why evt.lengthComputable is showing as false and evt.total is showing as 0 ? P.S : The URL has content-length header.
Is there any other way to track the real time download progress for JSON data?
Upvotes: 1
Views: 542
Reputation: 2650
According to this SO answer you should add the eventlisteners
to the upload
property of the xhr object. So your code should look like this:
$.ajax({
url: 'https://www.udacity.com/public-api/v0/courses',
xhr: function () {
console.log('xhr');
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener('loadend', uploadComplete, false); // <-- CHANGED LINE
function uploadComplete(event) {
console.log('uploadComplete');
}
xhr.upload.addEventListener("progress", function (evt) { // <-- CHANGED LINE
console.log(evt.percentComplete);
console.log([evt.lengthComputable, evt.loaded, evt.total]);
var percentComplete = (evt.loaded / evt.total) * 100;
console.log(percentComplete + "p")
}, false);
return xhr;
},
success: function (response) {
console.log("success")
}
});
Upvotes: 1