What is XMLHttpRequest?
When to choose XMLHttpRequest over Fetch API?
- Need to support older browsers but avoid using polyfills.
- For historical reasons, there is a lot of code that uses XMLHttpRequest that needs to be supported
- The Fetch API cannot yet provide tracking of the progress of sending to the server
How to use XMLHttpRequest?
XMLHttpRequest has two modes of operation: asynchronous and synchronous. In most cases, asynchronous requests are used. To make a request, we need to follow these steps:
1. Create an XMLHttpRequest object
2. Initialize the created object using the xhr.open() method:
- method: HTTP method
- URL: the URI where the request is sent (string or a URL object)
- async (optional): if set to false, then the request will be executed synchronously (default true)
- user, password (optional): login and password for basic HTTP authorization
3. Submit an request usin the xhr.send() method:
You need to listen to events on the xhr object in order to be notified when the status of a request changes. The most used events are:
- xhr.onload: occurs when any response is received from the server, including HTTP error responses
- xhr.onprogress: occurs periodically during a response (useful for showing the progress of the request)
- xhr.onreadystatechange: notifies when the status of an XMLHttpRequest has changed (e.g. the request has completed)
- xhr.onerror: indicates that the request could not be completed, for example, a connection could not be established or an invalid URL was specified
4. If you need to cancel the request, you can use the xhr.abort() method. This method generates an abort event and sets xhr.status to 0.
An example of sending a GET request to the ReqBin echo URL.
XMLHttpRequest always sends an asynchronous request unless otherwise specified. Below is an example of an async request to the ReqBin echo URL with XMLHttpRequest object:
How to post JSON data using XMLHttpRequest?
How to post HTML Form data using XMLHttpRequest?
How to post XML data using XMLHttpRequest?
How to set a timeout on XMLHttpRequest?
You can use the xhr.timeout property to set a timeout for an XMLHttpRequest. The timeout is specified in milliseconds. The default value is 0, which means the request has no timeout.