XMLHttpRequest.addEventListener vs XMLHttpRequest.upload.addEventListener

DMac the Destroyer picture DMac the Destroyer · Oct 17, 2012 · Viewed 14.8k times · Source

What is the difference between the this code block:

var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);

xhr.open("POST", "upload_url");
xhr.send(some_form_data);

and this:

var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.upload.addEventListener("load", uploadComplete, false);
xhr.upload.addEventListener("error", uploadFailed, false);
xhr.upload.addEventListener("abort", uploadCanceled, false);

xhr.open("POST", "upload_url");
xhr.send(some_form_data);

I've seen both implementations in blogs and other SO posts, but no one explains why they use one over the other. The only difference I can find at this point is that the latter doesn't work on the default Android browser, while the former seems to work on just about everything.

Answer

shawnXiao picture shawnXiao · Sep 18, 2013

According to the w3c specification about the XMLHttpRequest. http://www.w3.org/TR/XMLHttpRequest/#the-upload-attribute

As indicated earlier, each XMLHttpRequest object has an associated XMLHttpRequestUpload object.

Progress events exist for both download and upload transfers. The download events are fired on the XMLHttpRequest object itself, as shown in the above sample. The upload events are fired on the XMLHttpRequest.upload object