Advanced AJAX

Track AJAX Upload Progress with XMLHttpRequest

Display upload progress with XMLHttpRequest upload events and handle completion and failures.

Track AJAX Upload Progress with XMLHttpRequest

XMLHttpRequest exposes upload progress events, making it useful when an interface needs a percentage indicator. Fetch support for upload progress remains more limited in common browser APIs.

Upload with progress

const xhr = new XMLHttpRequest();
xhr.open('POST', '/api/upload.php');
xhr.upload.addEventListener('progress', (event) => {
  if (event.lengthComputable) {
    const percent = Math.round(event.loaded / event.total * 100);
    progress.value = percent;
  }
});
xhr.addEventListener('load', () => {
  if (xhr.status >= 200 && xhr.status < 300) {
    console.log('Upload complete');
  }
});
xhr.addEventListener('error', () => console.error('Network error'));
xhr.send(new FormData(form));

Improve the experience

Use a semantic progress element, announce status changes accessibly, and distinguish upload progress from server-side processing. A completed transfer does not necessarily mean the server has finished validating or processing the file.

Share this page Help other developers discover this resource.