Using XMLHttpRequest

  • Revision slug: DOM/XMLHttpRequest/Using_XMLHttpRequest
  • Revision title: Using XMLHttpRequest
  • Revision id: 362175
  • Created:
  • Creator: fusionchess
  • Is current revision? No
  • Comment Standard example: used an explicitly declared function as listener for the request

Revision Content

XMLHttpRequest makes sending HTTP requests very easy.  You simply create an instance of the object, open a URL, and send the request.  The HTTP status of the result, as well as the result's contents, are available in the request object when the transaction is completed. This page outlines some of the common and even slightly obscure use cases for this powerful JavaScript object.

function reqListener () {
  console.log(this.responseText);
};

var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
oReq.open("get", "yourFile.txt", true);
oReq.send();

Types of requests

A request made via XMLHttpRequest can fetch the data in one of two ways, asynchronously or synchronously. The type of request is dictated by the optional async argument (the third argument) that is set on the XMLHttpRequest open() method. If this argument is false or unspecified, then the XMLHttpRequest will be processed synchronously, otherwise the process will be done asynchronously. A detailed discussion and demonstrations of these two types of requests can be found on the synchronous and asynchronous requests page. In general, best practice dictates asynchronous requests to be best.

Handling responses

There are several types of response attributes defined by the W3C specification for XMLHttpRequest.  These tell the client making the XMLHttpRequest important information about the status of the response. Some cases where dealing with non-text response types may involve some manipulation and analysis as outlined in the following sections.

Analyzing and manipulating the responseXML property

If you use XMLHttpRequest to get the content of a remote XML document, the responseXML property will be a DOM Object containing a parsed XML document, which can be hard to manipulate and analyze. There are four primary ways of analyzing this XML document:

  1. Using XPath to address (point to) parts of it.
  2. Using JXON to convert it into a JavaScript Object tree.
  3. Manually Parsing and serializing XML to strings or objects.
  4. Using XMLSerializer to serialize DOM trees to strings or to files.
  5. RegExp can be used if you always know the content of the XML document beforehand. You might want to remove line breaks, if you use RegExp to scan with regard to linebreaks. However, this method is a "last resort" since if the XML code changes slightly, the method will likely fail.

Analyzing and manipulating a responseText property containing an HTML document

Note: The W3C XMLHttpRequest specification has added HTML parsing support to XMLHttpRequest, which originally supported only XML parsing. This feature allows Web apps to obtain an HTML resource as a parsed DOM using XMLHttpRequest.responseXML property. Read the article about HTML in XMLHttpRequest for details.

If you use XMLHttpRequest to get the content of a remote HTML webpage, the responseText property is a string containing a "soup" of all the HTML tags, which can be hard to manipulate and analyze. There are three primary ways of analyzing this HTML soup string:

  1. Safely parsing with nsIScriptableUnescapeHTML will quickly convert the HTML string into DOM, while stripping out JavaScript and other advanced elements, including the <head> of the webpage.
  2. RegExp can be used if you always know the content of the HTML responseText beforehand. You might want to remove line breaks, if you use RegExp to scan with regard to linebreaks. However, this method is a "last resort" since if the HTML code changes slightly, the method will likely fail.
  3. Using a hidden chrome or content-level iframe to load up the webpage can also be done to then manipulate it as DOM, however there are security risks to giving remote code this level of privileged access, which can cause issues for the review of your addon. For example, if a webpage executes the common "document.location = redirecttothispage.html" command on load, this will get interpreted as changing the browser chrome location (document.location in an extension) as opposed to the webpage location (content.document.location in an extension), thus destroying all browser components. Alternatively, and somewhat safer, a responseText string attained through a XMLHttpRequest can be analyzed using RegExp to remove potential JavaScript problems, then loaded into the hidden iframe that you have set up:
document.getElementById("hiddenXULiframe").contentWindow.document.body.innerHTML = req.responseText

Using FormData objects

The FormData object lets you compile a set of key/value pairs to send using XMLHttpRequest. Its primarily intended for use in sending form data, but can be used independently from forms in order to transmit keyed data. The transmitted data is in the same format that the form's submit() method would use to send the data if the form's encoding type were set to "multipart/form-data". FormData objects can be utilized in a number of ways with an XMLHttpRequest. For examples and explanations of how one can utilize FormData with XMLHttpRequests see the Using FormData Objects page.

Sending forms through the URL string

When a {{HTMLElement("form")}} uses the GET method, you can send its content directly through the URL string:

<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>MDN Example &ndash; AJAX and forms</title>
<script type="text/javascript">

function AJAXGet(oForm) {
  if (oForm.method.toLowerCase() !== "get") { return; }
  var query = [];
  var xhr = new XMLHttpRequest();
  for (var nItem = 0; nItem < oForm.elements.length; nItem++) {
    var field = oForm.elements[nItem];
    if (!field.hasAttribute("name") || (/^(?:radio|checkbox)$/.test(field.type) && !field.checked)) { continue; }
    query.push(escape(field.getAttribute("name")) + "=" + escape(field.value));
  }
  xhr.onload = function() {
    alert(this.responseText);
  };
  xhr.onerror = function() {
    alert("An error occurred while submitting the form.");
  };
  xhr.open("get", query.length ? oForm.action + "?" + query.join("&") : oForm.action, true);
  xhr.send(null);
}

</script>

</head>
 
<body>

  <form onsubmit="return AJAXGet(this), false;" action="test.php" method="get">
    <p>
      First name: <input type="text" name="firstname" /><br />
      Last name: <input type="text" name="lastname" /><br />
      Password: <input type="password" name="pwd" /><br />
      <input type="radio" name="sex" value="male" /> Male
      <input type="radio" name="sex" value="female" /> Female
    </p>
    <p>
      <input type="checkbox" name="vehicle" value="Bike" />I have a bike<br />
      <input type="checkbox" name="vehicle" value="Car" />I have a car
    </p>
    <p>
      <input type="submit" value="Submit" />
    </p>
  </form>

</body>
</html>

Handling binary data

Although XMLHttpRequest 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 an XMLHttpRequest into sending binary data. These involve utilizing the .overrideMimeType() method on the XMLHttpRequest object and is a workable solution.

var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
// retrieve data unprocessed as a binary string
xhr.overrideMimeType("text/plain; charset=x-user-defined");
/* ... */

The XMLHttpRequest Level 2 Specification adds new responseType attributes which make sending and receiving binary data much easier.

var xhr = new XMLHttpRequest();

xhr.open("GET", url, true);
xhr.responseType = "arraybuffer"; 
xhr.onload = function(e) {
  var arraybuffer = xhr.response; // not responseText
  /* ... */
}
xhr.send();

For more examples check out the Sending 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 DOM progress event monitoring of XMLHttpRequest transfers follows the Web API specification for progress events.

var req = new XMLHttpRequest();

req.addEventListener("progress", updateProgress, false);
req.addEventListener("load", transferComplete, false);
req.addEventListener("error", transferFailed, false);
req.addEventListener("abort", transferCanceled, false);

req.open();

...

// progress on transfers from the server to the client (downloads)
function updateProgress(evt) {
  if (evt.lengthComputable) {
    var percentComplete = evt.loaded / evt.total;
    ...
  } else {
    // Unable to compute progress information since the total size is unknown
  }
}

function transferComplete(evt) {
  alert("The transfer is complete.");
}

function transferFailed(evt) {
  alert("An error occurred while transferring the file.");
}

function transferCanceled(evt) {
  alert("The transfer has been canceled by the user.");
}

Lines 3-6 add event listeners for the various events that are sent while performing a data transfer using XMLHttpRequest.

Note: You need to add the event listeners before calling open() on the request.  Otherwise the progress events will not fire.

The progress event handler, specified by the updateProgress() 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's total and loaded fields.  However, if the lengthComputable 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 the XMLHttpRequest object itself, as shown in the above sample. The upload events are fired on the XMLHttpRequest.upload object, as shown below:

var req = new XMLHttpRequest();

req.upload.addEventListener("progress", updateProgress, false);
req.upload.addEventListener("load", transferComplete, false);
req.upload.addEventListener("error", transferFailed, false);
req.upload.addEventListener("abort", transferCanceled, false);

req.open();
Note: Progress events are not available for the file: protocol.

{{gecko_callout_heading("9.0")}}

Starting in Gecko 9.0 {{geckoRelease("9.0")}}, progress events can now be relied upon to 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.

{{gecko_callout_heading("12.0")}}

If your progress event is called with a responseType of "moz-blob", the value of response is a {{domxref("Blob")}} containing the data received so far.

One can also detect all three load-ending conditions (abort, load, or error) using the loadend event:

req.addEventListener("loadend", loadEnd, false);

function loadEnd(e) {
  alert("The transfer finished (although we don't know if it succeeded or not).");
} 

Note that there's no way to be certain from the information received by the loadend 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.

Cross-site XMLHttpRequest

Modern browsers support cross-site requests by implementing the web applications working group's Access Control for Cross-Site Requests standard.  As long as the server is configured to allow requests from your web application's origin, XMLHttpRequest will work.  Otherwise, an INVALID_ACCESS_ERR exception is thrown.

Bypassing the cache

A, cross-browser compatible approach to bypassing the cache is to append a timestamp to the URL, being sure to include a "?" or "&" as appropriate.  For example:

http://foo.com/bar.html -> http://foo.com/bar.html?12345
http://foo.com/bar.html?foobar=baz -> http://foo.com/bar.html?foobar=baz&12345

Since 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:

var req = new XMLHttpRequest();

req.open("GET", url + ((/\?/).test(url) ? "&" : "?") + (new Date()).getTime(), true);
req.send(null);

Security

{{fx_minversion_note(3, "Versions of Firefox prior to Firefox 3 allowed you to set the preference capability.policy.<policyname>.XMLHttpRequest.open</policyname> to allAccess to give specific sites cross-site access.  This is no longer supported.")}}

{{fx_minversion_note(5, "Versions of Firefox prior to Firefox 5 could use netscape.security.PrivilegeManager.enablePrivilege(\"UniversalBrowserRead\"); to request cross-site access. This is no longer supported, even though it produces no warning and permission dialog is still presented.")}}

The recommended way to enable cross-site scripting is to use the Access-Control-Allow-Origin HTTP header in the response to the XMLHttpRequest.

XMLHttpRequests being stopped

If you end up with an XMLHttpRequest having status=0 and statusText=null, it means that the request was not allowed to be performed. It was UNSENT. A likely cause for this is when the XMLHttpRequest origin (at the creation of the XMLHttpRequest) has changed when the XMLHttpRequest is then open(). This case can happen for example when one has an XMLHttpRequest that gets fired on an onunload event for a window: the XMLHttpRequest gets in fact created when the window to be closed is still there, and then the request is sent (ie open()) when this window has lost its focus and potentially different window has gained focus. The way to avoid this problem is to set a listener on the new window "activate" event that gets set when the old window has its "unload" event fired.

Using XMLHttpRequest from JavaScript modules / XPCOM components

Instantiating XMLHttpRequest from a JavaScript module or an XPCOM component works a little differently; it can't be instantiated using the XMLHttpRequest() constructor. The constructor is not defined inside components and the code results in an error. The best way to work around this is to use the XPCOM component constructor.

const XMLHttpRequest = Components.Constructor("@mozilla.org/xmlextras/xmlhttprequest;1");
var req = XMLHttpRequest();

Unfortunately in versions of Gecko prior to Gecko 16 there is a bug which can cause requests created this way to be cancelled for no reason.  If you need your code to work on Gecko 15 or earlier, you can get the XMLHttpRequest constructor from the hidden DOM window like so.

const { XMLHttpRequest } = Components.classes["@mozilla.org/appshell/appShellService;1"]
                                     .getService(Components.interfaces.nsIAppShellService)
                                     .hiddenDOMWindow;
var req = XMLHttpRequest();

See also

  1. MDC AJAX introduction
  2. HTTP access control
  3. How to check the security state of an XMLHTTPRequest over SSL
  4. XMLHttpRequest - REST and the Rich User Experience
  5. Microsoft documentation
  6. Apple developers' reference
  7. "Using the XMLHttpRequest Object" (jibbering.com)
  8. The XMLHttpRequest Object: W3C Specification
  9. Web Progress Events specification

Revision Source

<p><a href="/en-US/docs/DOM/XMLHttpRequest" title="XMLHttpRequest"><code>XMLHttpRequest</code></a> makes sending HTTP requests very easy.&nbsp; You simply create an instance of the object, open a URL, and send the request.&nbsp; The <a href="/en-US/docs/HTTP/HTTP_response_codes" title="HTTP response codes">HTTP status</a> of the result, as well as the result's contents, are available in the request object when the transaction is completed. This page outlines some of the common and even slightly obscure use cases for this powerful JavaScript object.</p>
<pre class="brush: js">
function reqListener () {
&nbsp; console.log(this.responseText);
};

var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
oReq.open("get", "yourFile.txt", true);
oReq.send();</pre>
<h2 id="Types_of_requests">Types of requests</h2>
<p>A request made via XMLHttpRequest can fetch the data in one of two ways, asynchronously or synchronously. The type of request is dictated by the optional <code>async</code> argument (the third argument) that is set on the XMLHttpRequest <a href="/en-US/docs/DOM/XMLHttpRequest#open" title="DOM/XMLHttpRequest#open()">open()</a> method. If this argument is false or unspecified, then the XMLHttpRequest will be processed synchronously, otherwise the process will be done asynchronously. A detailed discussion and demonstrations of these two types of requests can be found on the <a href="/en-US/docs/DOM/XMLHttpRequest/Synchronous_and_Asynchronous_Requests" title="Synchronous and Asynchronous Requests">synchronous and asynchronous requests</a> page. In general, best practice dictates asynchronous requests to be best.</p>
<h2 id="Handling_responses">Handling responses</h2>
<p>There are several types of <a href="http://www.w3.org/TR/XMLHttpRequest2/#response" title="http://www.w3.org/TR/XMLHttpRequest2/#response">response attributes</a> defined by the W3C specification for XMLHttpRequest.&nbsp; These tell the client making the XMLHttpRequest important information about the status of the response. Some<span style="line-height: 1.572;">&nbsp;cases where dealing with non-text response types may involve some manipulation and analysis as outlined in the following sections.</span></p>
<h3 id="Analyzing_and_manipulating_the_responseXML_property">Analyzing and manipulating the <code>responseXML</code> property</h3>
<p>If you use <code>XMLHttpRequest </code>to get the content of a remote XML document, the <code>responseXML </code>property will be a DOM Object containing a parsed XML document, which can be hard to manipulate and analyze. There are four primary ways of analyzing this XML document:</p>
<ol>
  <li>Using <a href="/en-US/docs/XPath" title="XPath">XPath</a> to address (point to) parts of it.</li>
  <li>Using <a href="/en-US/docs/JXON" title="JXON">JXON</a> to convert it into a JavaScript Object tree.</li>
  <li>Manually <a href="/en-US/docs/Parsing_and_serializing_XML" title="Parsing_and_serializing_XML">Parsing and serializing XML</a> to strings or objects.</li>
  <li>Using <a href="/en-US/docs/XMLSerializer" title="XMLSerializer">XMLSerializer</a> to serialize <strong>DOM trees to strings or to files</strong>.</li>
  <li><a href="/en-US/docs/JavaScript/Reference/Global_Objects/RegExp" title="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp">RegExp </a>can be used if you always know the content of the XML document beforehand. You might want to remove line breaks, if you use RegExp to scan with regard to linebreaks. However, this method is a "last resort" since if the XML code changes slightly, the method will likely fail.</li>
</ol>
<h3 id="Analyzing_and_manipulating_a_responseText_property_containing_an_HTML_document">Analyzing and manipulating a <code>responseText</code> property containing an HTML document</h3>
<div class="note">
  <strong>Note:</strong> The W3C <a href="http://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html">XMLHttpRequest</a> specification has added <strong>HTML parsing support to <a href="/en-US/docs/DOM/XMLHttpRequest" title="DOM/XMLHttpRequest"><code>XMLHttpRequest</code></a></strong>, which originally supported only XML parsing. This feature allows Web apps to obtain an HTML resource as a parsed DOM using <code>XMLHttpRequest.<strong>responseXML</strong></code> property. Read the article about <a href="/en-US/docs/HTML_in_XMLHttpRequest" title="HTML_in_XMLHttpRequest">HTML in XMLHttpRequest</a> for details.</div>
<p>If you use <code>XMLHttpRequest</code> to get the content of a remote HTML webpage, the <code>responseText</code> property is a string containing a "soup" of all the HTML tags, which can be hard to manipulate and analyze. There are three primary ways of analyzing this HTML soup string:</p>
<ol>
  <li><a href="/en-US/docs/Code_snippets/HTML_to_DOM#Safely_parsing_simple_HTML.c2.a0to_DOM" title="Code_snippets/HTML_to_DOM#Safely_parsing_simple_HTML.c2.a0to_DOM">Safely parsing with nsIScriptableUnescapeHTML</a> will quickly convert the HTML string into DOM, while stripping out JavaScript and other advanced elements, including the <code>&lt;head&gt;</code> of the webpage.</li>
  <li><a href="/en-US/docs/JavaScript/Reference/Global_Objects/RegExp" title="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp">RegExp </a>can be used if you always know the content of the HTML <code>responseText </code>beforehand. You might want to remove line breaks, if you use RegExp to scan with regard to linebreaks. However, this method is a "last resort" since if the HTML code changes slightly, the method will likely fail.</li>
  <li><a href="/en-US/docs/Code_snippets/HTML_to_DOM#Using_a_hidden_iframe_element_to_parse_HTML_to_a_window%27s_DOM" title="https://developer.mozilla.org/en/Code_snippets/HTML_to_DOM#Using_a_hidden_iframe_element_to_parse_HTML_to_a_window's_DOM">Using a hidden chrome or content-level iframe</a> to load up the webpage can also be done to then manipulate it as DOM, however there are <a href="/en-US/docs/Displaying_web_content_in_an_extension_without_security_issues" title="Displaying_web_content_in_an_extension_without_security_issues">security risks to giving remote code this level of privileged access</a>, which can cause <a class="link-https" href="https://addons.mozilla.org/en-US/developers/docs/policies/reviews" title="https://addons.mozilla.org/en-US/developers/docs/policies/reviews">issues </a>for the review of your addon. For example, if a webpage executes the common "<code>document.location = redirecttothispage.html</code>" command on load, this will get interpreted as changing the browser chrome location (<code>document.location</code> in an extension) as opposed to the webpage location (<code>content.document.location</code> in an extension), thus destroying all browser components. Alternatively, and somewhat safer, a <code>responseText </code>string attained through a <code>XMLHttpRequest </code>can be analyzed using RegExp to remove potential JavaScript problems, then loaded into the hidden iframe that you have set up:</li>
</ol>
<pre>
document.getElementById("hiddenXULiframe").contentWindow.document.body.innerHTML = req.responseText
</pre>
<h2 id="Using_FormData_objects">Using FormData objects</h2>
<p>The <a href="/en-US/docs/DOM/XMLHttpRequest/FormData" title="DOM/XMLHttpRequest/FormData"><code>FormData</code></a> object lets you compile a set of key/value pairs to send using <code>XMLHttpRequest</code>. Its primarily intended for use in sending form data, but can be used independently from forms in order to transmit keyed data. The transmitted data is in the same format that the form's <code>submit()</code> method would use to send the data if the form's encoding type were set to "multipart/form-data". FormData objects can be utilized in a number of ways with an XMLHttpRequest. For examples and explanations of how one can utilize FormData with XMLHttpRequests see the <a href="/en-US/docs/DOM/XMLHttpRequest/FormData/Using_FormData_Objects" title="Using FormData Objects">Using FormData Objects</a> page.</p>
<h2 id="Sending_forms_through_the_URL_string">Sending forms through the URL string</h2>
<p><strong>When a {{HTMLElement("form")}} uses the <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.3" title="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.3"><code>GET</code></a> <a href="/en-US/docs/DOM/form.method" title="HTML/Element/form#attr-method">method</a></strong>, you can send its content directly through the URL string:</p>
<pre class="brush: html">
&lt;!doctype html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /&gt;
&lt;title&gt;MDN Example &amp;ndash; AJAX and forms&lt;/title&gt;
&lt;script type="text/javascript"&gt;

function AJAXGet(oForm) {
  if (oForm.method.toLowerCase() !== "get") { return; }
  var query = [];
  var xhr = new XMLHttpRequest();
  for (var nItem = 0; nItem &lt; oForm.elements.length; nItem++) {
    var field = oForm.elements[nItem];
    if (!field.hasAttribute("name") || (/^(?:radio|checkbox)$/.test(field.type) &amp;&amp; !field.checked)) { continue; }
    query.push(escape(field.getAttribute("name")) + "=" + escape(field.value));
  }
  xhr.onload = function() {
    alert(this.responseText);
  };
  xhr.onerror = function() {
    alert("An error occurred while submitting the form.");
  };
  xhr.open("get", query.length ? oForm.action + "?" + query.join("&amp;") : oForm.action, true);
  xhr.send(null);
}

&lt;/script&gt;

&lt;/head&gt;
 
&lt;body&gt;

  &lt;form onsubmit="return AJAXGet(this), false;" action="test.php" method="get"&gt;
    &lt;p&gt;
      First name: &lt;input type="text" name="firstname" /&gt;&lt;br /&gt;
      Last name: &lt;input type="text" name="lastname" /&gt;&lt;br /&gt;
      Password: &lt;input type="password" name="pwd" /&gt;&lt;br /&gt;
      &lt;input type="radio" name="sex" value="male" /&gt; Male
      &lt;input type="radio" name="sex" value="female" /&gt; Female
    &lt;/p&gt;
    &lt;p&gt;
      &lt;input type="checkbox" name="vehicle" value="Bike" /&gt;I have a bike&lt;br /&gt;
      &lt;input type="checkbox" name="vehicle" value="Car" /&gt;I have a car
    &lt;/p&gt;
    &lt;p&gt;
      &lt;input type="submit" value="Submit" /&gt;
    &lt;/p&gt;
  &lt;/form&gt;

&lt;/body&gt;
&lt;/html&gt;</pre>
<h2 id="Handling_binary_data">Handling binary data</h2>
<p>Although <code>XMLHttpRequest</code> 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 an XMLHttpRequest into sending binary data. These involve utilizing the .overrideMimeType() method on the XMLHttpRequest object and is a workable solution.</p>
<pre class="brush:js">
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
// retrieve data unprocessed as a binary string
xhr.overrideMimeType("text/plain; charset=x-user-defined");
/* ... */
</pre>
<p>The XMLHttpRequest Level 2 Specification adds new <a href="http://www.w3.org/TR/XMLHttpRequest2/#the-responsetype-attribute" title="http://www.w3.org/TR/XMLHttpRequest2/#the-responsetype-attribute">responseType attributes</a> which make sending and receiving binary data much easier.</p>
<pre class="brush:js">
var xhr = new XMLHttpRequest();

xhr.open("GET", url, true);
xhr.responseType = "arraybuffer"; 
xhr.onload = function(e) {
  var arraybuffer = xhr.response; // not responseText
  /* ... */
}
xhr.send();
</pre>
<p>For more examples check out the <a href="/en-US/docs/DOM/XMLHttpRequest/Sending_and_Receiving_Binary_Data" title="DOM/XMLHttpRequest/Sending_and_Receiving_Binary_Data">Sending and Receiving Binary Data</a> page</p>
<h2 id="Monitoring_progress">Monitoring progress</h2>
<p><code>XMLHttpRequest</code> 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.</p>
<p>Support for DOM progress event monitoring of <code>XMLHttpRequest</code> transfers follows the Web API <a href="http://dev.w3.org/2006/webapi/progress/Progress.html" title="http://dev.w3.org/2006/webapi/progress/Progress.html">specification for progress events</a>.</p>
<pre class="brush:js">
var req = new XMLHttpRequest();

req.addEventListener("progress", updateProgress, false);
req.addEventListener("load", transferComplete, false);
req.addEventListener("error", transferFailed, false);
req.addEventListener("abort", transferCanceled, false);

req.open();

...

// progress on transfers from the server to the client (downloads)
function updateProgress(evt) {
  if (evt.lengthComputable) {
    var percentComplete = evt.loaded / evt.total;
    ...
  } else {
    // Unable to compute progress information since the total size is unknown
  }
}

function transferComplete(evt) {
  alert("The transfer is complete.");
}

function transferFailed(evt) {
  alert("An error occurred while transferring the file.");
}

function transferCanceled(evt) {
  alert("The transfer has been canceled by the user.");
}</pre>
<p>Lines 3-6 add event listeners for the various events that are sent while performing a data transfer using <code>XMLHttpRequest</code>.</p>
<div class="note">
  <strong>Note:</strong> You need to add the event listeners before calling <code>open()</code> on the request. &nbsp;Otherwise the progress events will not fire.</div>
<p>The progress event handler, specified by the <code>updateProgress()</code> 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's <code>total</code> and <code>loaded</code> fields.&nbsp; However, if the <code>lengthComputable</code> field is false, the total length is not known and will be zero.</p>
<p>Progress events exist for both download and upload transfers. The download events are fired on the <code>XMLHttpRequest</code> object itself, as shown in the above sample. The upload events are fired on the <code>XMLHttpRequest.upload</code> object, as shown below:</p>
<pre class="brush:js">
var req = new XMLHttpRequest();

req.upload.addEventListener("progress", updateProgress, false);
req.upload.addEventListener("load", transferComplete, false);
req.upload.addEventListener("error", transferFailed, false);
req.upload.addEventListener("abort", transferCanceled, false);

req.open();
</pre>
<div class="note">
  <strong>Note:</strong> Progress events are not available for the <code>file:</code> protocol.</div>
<div class="geckoVersionNote" style="undefined">
  <p>{{gecko_callout_heading("9.0")}}</p>
  <p>Starting in Gecko 9.0 {{geckoRelease("9.0")}}, progress events can now be relied upon to 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.</p>
</div>
<div class="geckoVersionNote">
  <p>{{gecko_callout_heading("12.0")}}</p>
  <p>If your progress event is called with a <code>responseType</code> of "moz-blob", the value of response is a {{domxref("Blob")}} containing the data received so far.</p>
</div>
<p>One can also detect all three load-ending conditions (<code>abort</code>, <code>load</code>, or <code>error</code>) using the <code>loadend</code> event:</p>
<pre class="brush:js">
req.addEventListener("loadend", loadEnd, false);

function loadEnd(e) {
  alert("The transfer finished (although we don't know if it succeeded or not).");
} 
</pre>
<p>Note that there's no way to be certain from the information received by the <code>loadend</code> 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.</p>
<h2 id="Cross-site_XMLHttpRequest">Cross-site XMLHttpRequest</h2>
<p>Modern browsers support cross-site requests by implementing the web applications working group's <a href="/en-US/docs/HTTP_access_control" title="HTTP access control">Access Control for Cross-Site Requests</a> standard.&nbsp; As long as the server is configured to allow requests from your web application's origin, <code>XMLHttpRequest</code> will work.&nbsp; Otherwise, an <code>INVALID_ACCESS_ERR</code> exception is thrown.</p>
<h2 id="Bypassing_the_cache">Bypassing the cache</h2>
<p><span style="line-height: 1.572;">A, cross-browser compatible approach to bypassing the cache is to append a timestamp to the URL, being sure to include a "?" or "&amp;" as appropriate.&nbsp; For example:</span></p>
<pre>
http://foo.com/bar.html -&gt; http://foo.com/bar.html?12345
http://foo.com/bar.html?foobar=baz -&gt; http://foo.com/bar.html?foobar=baz&amp;12345
</pre>
<p>Since the local cache is indexed by URL, this causes every request to be unique, thereby bypassing the cache.</p>
<p>You can automatically adjust URLs using the following code:</p>
<pre class="brush:js">
var req = new XMLHttpRequest();

req.open("GET", url + ((/\?/).test(url) ? "&amp;" : "?") + (new Date()).getTime(), true);
req.send(null);</pre>
<h2 id="Security">Security</h2>
<p>{{fx_minversion_note(3, "Versions of Firefox prior to Firefox 3 allowed you to set the preference <code>capability.policy.<policyname>.XMLHttpRequest.open</policyname></code> to <code>allAccess</code> to give specific sites cross-site access.&nbsp; This is no longer supported.")}}</p>
<p>{{fx_minversion_note(5, "Versions of Firefox prior to Firefox 5 could use <code>netscape.security.PrivilegeManager.enablePrivilege(\"UniversalBrowserRead\");</code> to request cross-site access. This is no longer supported, even though it produces no warning and permission dialog is still presented.")}}</p>
<p>The recommended way to enable cross-site scripting is to use the <code>Access-Control-Allow-Origin </code> HTTP header in the response to the XMLHttpRequest.</p>
<h3 id="XMLHttpRequests_being_stopped">XMLHttpRequests being stopped</h3>
<p>If you end up with an XMLHttpRequest having <code>status=0</code> and <code>statusText=null</code>, it means that the request was not allowed to be performed. It was <code><a href="http://www.w3.org/TR/XMLHttpRequest/#dom-xmlhttprequest-unsent" title="http://www.w3.org/TR/XMLHttpRequest/#dom-xmlhttprequest-unsent">UNSENT</a></code>. A likely cause for this is when the <a href="http://www.w3.org/TR/XMLHttpRequest/#xmlhttprequest-origin" style="outline: 1px dotted; outline-offset: 0pt;"><code>XMLHttpRequest</code> origin</a> (at the creation of the XMLHttpRequest) has changed when the XMLHttpRequest is then <code>open()</code>. This case can happen for example when one has an XMLHttpRequest that gets fired on an onunload event for a window: the XMLHttpRequest gets in fact created when the window to be closed is still there, and then the request is sent (ie <code>open()</code>) when this window has lost its focus and potentially different window has gained focus. The way to avoid this problem is to set a listener on the new window "activate" event that gets set when the old window has its "unload" event fired.</p>
<h2 id="Using_XMLHttpRequest_from_JavaScript_modules_.2F_XPCOM_components">Using XMLHttpRequest from JavaScript modules / XPCOM components</h2>
<p>Instantiating <code>XMLHttpRequest</code> from a <a href="/en-US/docs/JavaScript_code_modules/Using" title="https://developer.mozilla.org/en/JavaScript_code_modules/Using_JavaScript_code_modules">JavaScript module</a> or an XPCOM component works a little differently; it can't be instantiated using the <code>XMLHttpRequest()</code> constructor. The constructor is not defined inside components and the code results in an error. The best way to work around this is to use the XPCOM component constructor.</p>
<pre class="brush:js">
const XMLHttpRequest = Components.Constructor("@mozilla.org/xmlextras/xmlhttprequest;1");
var req = XMLHttpRequest();</pre>
<p>Unfortunately in versions of Gecko prior to Gecko 16 there is a bug which can cause requests created this way to be cancelled for no reason.&nbsp; If you need your code to work on Gecko 15 or earlier, you can get the XMLHttpRequest constructor from the hidden DOM window like so.</p>
<pre class="brush:js">
const { XMLHttpRequest } = Components.classes["@mozilla.org/appshell/appShellService;1"]
                                     .getService(Components.interfaces.nsIAppShellService)
                                     .hiddenDOMWindow;
var req = XMLHttpRequest();
</pre>
<h2 id="See_also">See also</h2>
<ol>
  <li><a href="/en-US/docs/AJAX/Getting_Started" title="AJAX/Getting_Started">MDC AJAX introduction</a></li>
  <li><a href="/en-US/docs/HTTP_access_control" title="HTTP access control">HTTP access control</a></li>
  <li><a href="/en-US/docs/How_to_check_the_security_state_of_an_XMLHTTPRequest_over_SSL" title="How to check the security state of an XMLHTTPRequest over SSL">How to check the security state of an XMLHTTPRequest over SSL</a></li>
  <li><a href="http://www.peej.co.uk/articles/rich-user-experience.html">XMLHttpRequest - REST and the Rich User Experience</a></li>
  <li><a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/xmlsdk/html/xmobjxmlhttprequest.asp">Microsoft documentation</a></li>
  <li><a href="http://developer.apple.com/internet/webcontent/xmlhttpreq.html">Apple developers' reference</a></li>
  <li><a href="http://jibbering.com/2002/4/httprequest.html">"Using the XMLHttpRequest Object" (jibbering.com)</a></li>
  <li><a href="http://www.w3.org/TR/XMLHttpRequest/">The XMLHttpRequest Object: W3C Specification</a></li>
  <li><a href="http://dev.w3.org/2006/webapi/progress/Progress.html" title="http://dev.w3.org/2006/webapi/progress/Progress.html">Web Progress Events specification</a></li>
</ol>
Revert to this revision