Using XMLHttpRequest
BaselineWidely available *
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
* Some parts of this feature may have varying levels of support.
In this guide, we'll take a look at how to useXMLHttpRequest
to issueHTTP requests in order to exchange data between the website and a server.
Examples of both common and more obscure use cases forXMLHttpRequest
are included.
To send an HTTP request:
- Create an
XMLHttpRequest
object - Open a URL
- Send the request.
After the transaction completes, theXMLHttpRequest
object will contain useful information such as the response body and theHTTP status of the result.
function reqListener() { console.log(this.responseText);}const req = new XMLHttpRequest();req.addEventListener("load", reqListener);req.open("GET", "http://www.example.org/example.txt");req.send();
Types of requests
A request made viaXMLHttpRequest
can fetch the data in one of two ways, asynchronously or synchronously. The type of request is dictated by the optionalasync
argument (the third argument) that is set on theXMLHttpRequest.open()
method. If this argument istrue
or not specified, theXMLHttpRequest
is processed asynchronously, otherwise the process is handled synchronously. A detailed discussion and demonstrations of these two types of requests can be found on thesynchronous and asynchronous requests page. You can't use synchronous requests outside web workers as it freezes the main interface.
Note:The constructorXMLHttpRequest
isn't limited to only XML documents. It starts with"XML" because when it was created the main format that was originally used for asynchronous data exchange was XML.
Handling responses
There are several types ofresponse attributes defined for theXMLHttpRequest()
constructor. These tell the client making theXMLHttpRequest
important information about the status of the response. Some cases where dealing with non-text response types may involve some manipulation and analysis are outlined in the following sections.
Analyzing and manipulating the responseXML property
If you useXMLHttpRequest
to get the content of a remote XML document, theresponseXML
property will be a DOM object containing a parsed XML document. This could prove difficult to manipulate and analyze. There are four primary ways of analyzing this XML document:
- UsingXPath to address (or point to) parts of it.
- ManuallyParsing and serializing XML to strings or objects.
- Using
XMLSerializer
to serializeDOM trees to strings or to files. RegExp
can be used if you always know the content of the XML document beforehand. You might want to remove line breaks, if you useRegExp
to scan with regard to line breaks. However, this method is a "last resort" since if the XML code changes slightly, the method will likely fail.
Note:XMLHttpRequest
can now interpret HTML for you, using theresponseXML
property. Read the article aboutHTML in XMLHttpRequest to learn how to do this.
Processing aresponseText
property containing an HTML document
If you useXMLHttpRequest
to get the content of a remote HTML webpage, theresponseText
property is a string containing the raw HTML. This could prove difficult to manipulate and analyze. There are three primary ways to analyze and parse this raw HTML string:
- Use the
XMLHttpRequest.responseXML
property as covered in the articleHTML in XMLHttpRequest. - Inject the content into the body of adocument fragment via
fragment.body.innerHTML
and traverse the DOM of the fragment. RegExp
can be used if you always know the content of the HTMLresponseText
beforehand. You might want to remove line breaks, if you useRegExp
to scan with regard to line breaks. However, this method is a "last resort" since if the HTML code changes slightly, the method will likely fail.
Handling binary data
AlthoughXMLHttpRequest
is most commonly used to send and receive textual data, it can be used to send and receive binary content. There are several well tested methods for coercing the response of anXMLHttpRequest
into sending binary data. These involve utilizing theoverrideMimeType()
method on theXMLHttpRequest
object and is a workable solution.
const req = new XMLHttpRequest();req.open("GET", url);// retrieve data unprocessed as a binary stringreq.overrideMimeType("text/plain; charset=x-user-defined");/* … */
However, more modern techniques are available, since theresponseType
attribute now supports a number of additional content types, which makes sending and receiving binary data much easier.
For example, consider this snippet, which uses theresponseType
of"arraybuffer"
to fetch the remote content into aArrayBuffer
object, which stores the raw binary data.
const req = new XMLHttpRequest();req.onload = (e) => { const arraybuffer = req.response; // not responseText /* … */};req.open("GET", url);req.responseType = "arraybuffer";req.send();
For more examples check out theSending and Receiving Binary Data page.
Monitoring progress
XMLHttpRequest
provides the ability to listen to various events that can occur while the request is being processed. This includes periodic progress notifications, error notifications, and so forth.
Support for DOMprogress
event monitoring ofXMLHttpRequest
transfers follows thespecification for progress events: these events implement theProgressEvent
interface. The actual events you can monitor to determine the state of an ongoing transfer are:
progress
The amount of data that has been retrieved has changed.
load
The transfer is complete; all data is now in the
response
const req = new XMLHttpRequest();req.addEventListener("progress", updateProgress);req.addEventListener("load", transferComplete);req.addEventListener("error", transferFailed);req.addEventListener("abort", transferCanceled);req.open();// …// progress on transfers from the server to the client (downloads)function updateProgress(event) { if (event.lengthComputable) { const percentComplete = (event.loaded / event.total) * 100; // … } else { // Unable to compute progress information since the total size is unknown }}function transferComplete(evt) { console.log("The transfer is complete.");}function transferFailed(evt) { console.log("An error occurred while transferring the file.");}function transferCanceled(evt) { console.log("The transfer has been canceled by the user.");}
We add event listeners for the various events that are sent while performing a data transfer usingXMLHttpRequest
.
Note:You need to add the event listeners before callingopen()
on the request. Otherwise theprogress
events will not fire.
The progress event handler, specified by theupdateProgress()
function in this example, receives the total number of bytes to transfer as well as the number of bytes transferred so far in the event'stotal
andloaded
fields. However, if thelengthComputable
field is false, the total length is not known and will be zero.
Progress events exist for both download and upload transfers. The download events are fired on theXMLHttpRequest
object itself, as shown in the above sample. The upload events are fired on theXMLHttpRequest.upload
object, as shown below:
const req = new XMLHttpRequest();req.upload.addEventListener("progress", updateProgress);req.upload.addEventListener("load", transferComplete);req.upload.addEventListener("error", transferFailed);req.upload.addEventListener("abort", transferCanceled);req.open();
Note:Progress events are not available for thefile:
protocol.
Progress events come in for every chunk of data received, including the last chunk in cases in which the last packet is received and the connection closed before the progress event is fired. In this case, the progress event is automatically fired when the load event occurs for that packet. This lets you now reliably monitor progress by only watching the "progress" event.
One can also detect all three load-ending conditions (abort
,load
, orerror
) using theloadend
event:
req.addEventListener("loadend", loadEnd);function loadEnd(e) { console.log( "The transfer finished (although we don't know if it succeeded or not).", );}
Note there is no way to be certain, from the information received by theloadend
event, as to which condition caused the operation to terminate; however, you can use this to handle tasks that need to be performed in all end-of-transfer scenarios.
Get last modified date
function getHeaderTime() { console.log(this.getResponseHeader("Last-Modified")); // A valid GMTString date or null}const req = new XMLHttpRequest();req.open( "HEAD", // use HEAD when you only need the headers "your-page.html",);req.onload = getHeaderTime;req.send();
Do something when last modified date changes
Let's create two functions:
function getHeaderTime() { const lastVisit = parseFloat( window.localStorage.getItem(`lm_${this.filepath}`), ); const lastModified = Date.parse(this.getResponseHeader("Last-Modified")); if (isNaN(lastVisit) || lastModified > lastVisit) { window.localStorage.setItem(`lm_${this.filepath}`, Date.now()); isFinite(lastVisit) && this.callback(lastModified, lastVisit); }}function ifHasChanged(URL, callback) { const req = new XMLHttpRequest(); req.open("HEAD" /* use HEAD - we only need the headers! */, URL); req.callback = callback; req.filepath = URL; req.onload = getHeaderTime; req.send();}
And to test:
// Let's test the file "your-page.html"ifHasChanged("your-page.html", function (modified, visit) { console.log( `The page '${this.filepath}' has been changed on ${new Date( modified, ).toLocaleString()}!`, );});
If you want to know if the current page has changed, refer to the article aboutdocument.lastModified
.
Cross-site XMLHttpRequest
Modern browsers support cross-site requests by implementing theCross-Origin Resource Sharing (CORS) standard. As long as the server is configured to allow requests from your web application's origin,XMLHttpRequest
will work. Otherwise, anINVALID_ACCESS_ERR
exception is thrown.
Bypassing the cache
A cross-browser compatible approach to bypassing the cache is appending a timestamp to the URL, being sure to include a "?" or "&" as appropriate. For example:
http://example.com/bar.html -> http://example.com/bar.html?12345http://example.com/bar.html?foobar=baz -> http://example.com/bar.html?foobar=baz&12345
As the local cache is indexed by URL, this causes every request to be unique, thereby bypassing the cache.
You can automatically adjust URLs using the following code:
const req = new XMLHttpRequest();req.open("GET", url + (/\?/.test(url) ? "&" : "?") + new Date().getTime());req.send(null);
Security
The recommended way to enable cross-site scripting is to use theAccess-Control-Allow-Origin
HTTP header in the response to the XMLHttpRequest.
XMLHttpRequests being stopped
If you conclude with an XMLHttpRequest receivingstatus=0
andstatusText=null
, this means the request was not allowed to be performed. It wasUNSENT
. A likely cause for this is when theXMLHttpRequest
origin (at the creation of the XMLHttpRequest) has changed when the XMLHttpRequest is subsequentlyopen()
. This case can happen, for example, when one has an XMLHttpRequest that gets fired on an onunload event for a window, the expected XMLHttpRequest is created when the window to be closed is still there, and finally sending the request (in other words,open()
) when this window has lost its focus and another window gains focus. The most effective way to avoid this problem is to set a listener on the new window'sDOMActivate
event which is set once the terminated window has itsunload
event triggered.
Specifications
Specification |
---|
XMLHttpRequest # interface-xmlhttprequest |