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 an HTTP 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?
To post HTML data with an XMLHttpRequest, you need to set "Content-Type" to "application/x-www-form-urlencoded" and pass the form data as key=value pairs to the xhr.send() method. Below is an example of sending HTML Form data to the ReqBin echo URL.
How to post XML data using XMLHttpRequest?
To send data in XML format using XMLHttpRequest, you need to set "Content-Type" to "application/xml" and pass XML string to the xhr.send() method. Below is an example of sending XML data to the ReqBin echo URL.
How to set a timeout on XMLHttpRequest?
The xhr.timeout property represents the number of milliseconds a request can take before being aborted. The default value is 0, which means the request does not have a timeout.