Categories
JavaScript Answers

How to get progress from XMLHttpRequest with JavaScript?

Spread the love

To get progress from XMLHttpRequest with JavaScript, we can set the onprogress property to a function that gets the request’s progress.

For instance, we write

const progressBar = document.getElementById("p");
const client = new XMLHttpRequest();
client.open("GET", "/foo/bar");
client.onprogress = (pe) => {
  if (pe.lengthComputable) {
    progressBar.max = pe.total;
    progressBar.value = pe.loaded;
  }
};
client.onloadend = (pe) => {
  progressBar.value = pe.loaded;
};
client.send();

to create the XMLHttpRequest client.

Then we call open to make a get request to /foo/bar.

We then set client.onprogress to a function that gets the progress from toe pe.total and pe.loaded properties.

loaded has the amount of data in bytes that arrived and total has the total number of bytes that we’re supposed to get.

Then we call client.send to make the request.

Conclusion

To get progress from XMLHttpRequest with JavaScript, we can set the onprogress property to a function that gets the request’s progress.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *