5

I'm trying to get the progress of an ajax request via the following code:

var xhr = new XMLHttpRequest();


xhr.addEventListener('progress', function(event) {

    console.log(event.loaded / event.total);
},
false);

xhr.addEventListener('load', function() {

    console.log('load');
},
false);


xhr.open('get', 'test.php', true);
xhr.send();

The problem is, the progress event only fires once, right before the load event (that is, in Webkit, it doesn't seem to work under Gecko).

Am I doing something wrong or is it just not supported properly?

DADU
  • 6,482
  • 7
  • 42
  • 64
  • Are you testing in localhost? – zatatatata Nov 07 '11 at 17:02
  • Yes but the remote host gives the same result. – DADU Nov 07 '11 at 17:13
  • 2
    Maybe this does help: http://stackoverflow.com/questions/76976/how-to-get-progress-from-xmlhttprequest – Fabian Nov 07 '11 at 17:18
  • @Fabian The answer, http://stackoverflow.com/questions/76976/how-to-get-progress-from-xmlhttprequest/3694435#3694435 relies on PHP's readfile. I can't use that because I expect to receive an HTML image element as responseText instead of raw image data. – DADU Nov 07 '11 at 18:22
  • Just make sure your webserver is configured to send the content-length header. – Gerben Nov 07 '11 at 18:38
  • @Gerben Checked the ajax request in Firebug and the content-length header is set. – DADU Nov 07 '11 at 18:43
  • That is all the PHP does. So the script should just work. How large is your test file, and are you testing locally? It could just be that it is loaded before the browser is willing to send a progress event. – Gerben Nov 07 '11 at 19:19
  • How big is the response? If it's tiny, it's possible that it simply loads so fast. – zatatatata Nov 08 '11 at 08:17
  • Will test again with a couple of megabytes. – DADU Nov 08 '11 at 17:18

1 Answers1

11

Use

xhr.upload.addEventListener('progress', function(event) { ... });

(note the added .upload)

Hernan S.
  • 2,604
  • 3
  • 17
  • 15
  • 4
    The OP said "DOWNLOAD" in the question, your answer would provide information on the upload portion – Ross Jul 04 '14 at 20:25