Using XMLHttpRequest

  • Revision slug: Web/API/XMLHttpRequest/Using_XMLHttpRequest
  • Revision title: Using XMLHttpRequest
  • Revision id: 430509
  • Created:
  • Creator: fusionchess
  • Is current revision? No
  • Comment Added paragraph "Get last modified date"

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 true or not specified, the XMLHttpRequest is processed asynchronously, otherwise the process is handled synchronously. A detailed discussion and demonstrations of these two types of requests can be found on the synchronous and asynchronous requests page. In general, you should rarely if ever use synchronous requests.

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

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 oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
// retrieve data unprocessed as a binary string
oReq.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 oReq = new XMLHttpRequest();

oReq.open("GET", url, true);
oReq.responseType = "arraybuffer";
oReq.onload = function(e) {
  var arraybuffer = oReq.response; // not responseText
  /* ... */
}
oReq.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: these events implement the {{domxref("ProgressEvent")}} interface.

var oReq = new XMLHttpRequest();

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

oReq.open();

// ...

// progress on transfers from the server to the client (downloads)
function updateProgress (oEvent) {
  if (oEvent.lengthComputable) {
    var percentComplete = oEvent.loaded / oEvent.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 oReq = new XMLHttpRequest();

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

oReq.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.

Submitting forms and uploading files

Instances of XMLHttpRequest can be used to submit forms in two ways:

  • using nothing but pure AJAX,
  • using the FormData API.

The second way (using the FormData API) is the simplest and the fastest, but has the disadvantage that the data thus collected can not be stringified: they are in every way a blob. It is the best solution for simple cases.
The first way (pure AJAX) is instead the most complex, but in compensation is also the most flexible and powerful: it lends itself to wider uses and the data thus collected can be stringified and reused for other purposes such as, for example, populating the status object during a manipulation of the browser history, or other.

Using nothing but pure AJAX

Submitting forms without the FormData API does not require other APIs, except that, only if you want to upload one or more files, the FileReader API.

A brief introduction to the submit methods

An html {{ HTMLElement("form") }} can be sent in four ways:

  • using the POST method and setting the enctype attribute to application/x-www-form-urlencoded (default);
  • using the POST method and setting the enctype attribute to text/plain;
  • using the POST method and setting the enctype attribute to multipart/form-data;
  • using the GET method (in this case the enctype attribute will be ignored).

Now, consider to submit a form containing only two fields, named foo and baz. If you are using the POST method, the server will receive a string similar to one of the following three ones depending on the encoding type you are using:

  • Method: POST; Encoding type: application/x-www-form-urlencoded (default):

    Content-Type: application/x-www-form-urlencoded
    
    foo=bar&baz=The+first+line.&#37;0D%0AThe+second+line.%0D%0A
  • Method: POST; Encoding type: text/plain:

    Content-Type: text/plain
    
    foo=bar
    baz=The first line.
    The second line.
  • Method: POST; Encoding type: multipart/form-data:

    Content-Type: multipart/form-data; boundary=---------------------------314911788813839
    
    -----------------------------314911788813839
    Content-Disposition: form-data; name="foo"
    
    bar
    -----------------------------314911788813839
    Content-Disposition: form-data; name="baz"
    
    The first line.
    The second line.
    
    -----------------------------314911788813839--

Instead, if you are using the GET method, a string like the following will be simply added to the URL:

?foo=bar&baz=The%20first%20line.%0AThe%20second%20line.

A little vanilla framework

All these things are done automatically by the web browser whenever you submit a {{ HTMLElement("form") }}. But if you want to do the same things using JavaScript you have to instruct the interpreter about all things. So, how to send forms in pure AJAX is too complex to be explained in detail here. For this reason we posted here a complete (but still didactic) framework, which is able to use all the four ways of submit and, also, to upload files:

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

"use strict";

/*\
|*|
|*|  :: XMLHttpRequest.prototype.sendAsBinary() Polifyll ::
|*|
|*|  https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#sendAsBinary()
\*/

if (!XMLHttpRequest.prototype.sendAsBinary) {
  XMLHttpRequest.prototype.sendAsBinary = function (sData) {
    var nBytes = sData.length, ui8Data = new Uint8Array(nBytes);
    for (var nIdx = 0; nIdx < nBytes; nIdx++) {
      ui8Data[nIdx] = sData.charCodeAt(nIdx) & 0xff;
    }
    /* send as ArrayBufferView...: */
    this.send(ui8Data);
    /* ...or as ArrayBuffer (legacy)...: this.send(ui8Data.buffer); */
  };
}

/*\
|*|
|*|  :: AJAX Form Submit Framework ::
|*|
|*|  https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest
|*|
|*|  This framework is released under the GNU Public License, version 3 or later.
|*|  http://www.gnu.org/licenses/gpl-3.0-standalone.html
|*|
|*|  Syntax:
|*|
|*|   AJAXSubmit(HTMLFormElement);
\*/

var AJAXSubmit = (function () {

  function ajaxSuccess () {
    /* console.log("AJAXSubmit - Success!"); */
    alert(this.responseText);
    /* you can get the serialized data through the "submittedData" custom property: */
    /* alert(JSON.stringify(this.submittedData)); */
  }

  function submitData (oData) {
    /* the AJAX request... */
    var oAjaxReq = new XMLHttpRequest();
    oAjaxReq.submittedData = oData;
    oAjaxReq.onload = ajaxSuccess;
    if (oData.technique === 0) {
      /* method is GET */
      oAjaxReq.open("get", oData.receiver.replace(/(?:\?.*)?$/, oData.segments.length > 0 ? "?" + oData.segments.join("&") : ""), true);
      oAjaxReq.send(null);
    } else {
      /* method is POST */
      oAjaxReq.open("post", oData.receiver, true);
      if (oData.technique === 3) {
        /* enctype is multipart/form-data */
        var sBoundary = "---------------------------" + Date.now().toString(16);
        oAjaxReq.setRequestHeader("Content-Type", "multipart\/form-data; boundary=" + sBoundary);
        oAjaxReq.sendAsBinary("--" + sBoundary + "\r\n" + oData.segments.join("--" + sBoundary + "\r\n") + "--" + sBoundary + "--\r\n");
      } else {
        /* enctype is application/x-www-form-urlencoded or text/plain */
        oAjaxReq.setRequestHeader("Content-Type", oData.contentType);
        oAjaxReq.send(oData.segments.join(oData.technique === 2 ? "\r\n" : "&"));
      }
    }
  }

  function processStatus (oData) {
    if (oData.status > 0) { return; }
    /* the form is now totally serialized! do something before sending it to the server... */
    /* doSomething(oData); */
    /* console.log("AJAXSubmit - The form is now serialized. Submitting..."); */
    submitData (oData);
  }

  function pushSegment (oFREvt) {
    this.owner.segments[this.segmentIdx] += oFREvt.target.result + "\r\n";
    this.owner.status--;
    processStatus(this.owner);
  }

  function plainEscape (sText) {
    /* how should I treat a text/plain form encoding? what characters are not allowed? this is what I suppose...: */
    /* "4\3\7 - Einstein said E=mc2" ----> "4\\3\\7\ -\ Einstein\ said\ E\=mc2" */
    return sText.replace(/[\s\=\\]/g, "\\$&");
  }

  function SubmitRequest (oTarget) {
    var nFile, sFieldType, oField, oSegmReq, oFile, bIsPost = oTarget.method.toLowerCase() === "post";
    /* console.log("AJAXSubmit - Serializing form..."); */
    this.contentType = bIsPost && oTarget.enctype ? oTarget.enctype : "application\/x-www-form-urlencoded";
    this.technique = bIsPost ? this.contentType === "multipart\/form-data" ? 3 : this.contentType === "text\/plain" ? 2 : 1 : 0;
    this.receiver = oTarget.action;
    this.status = 0;
    this.segments = [];
    var fFilter = this.technique === 2 ? plainEscape : escape;
    for (var nItem = 0; nItem < oTarget.elements.length; nItem++) {
      oField = oTarget.elements[nItem];
      if (!oField.hasAttribute("name")) { continue; }
      sFieldType = oField.nodeName.toUpperCase() === "INPUT" ? oField.getAttribute("type").toUpperCase() : "TEXT";
      if (sFieldType === "FILE" && oField.files.length > 0) {
        if (this.technique === 3) {
          /* enctype is multipart/form-data */
          for (nFile = 0; nFile < oField.files.length; nFile++) {
            oFile = oField.files[nFile];
            oSegmReq = new FileReader();
            /* (custom properties:) */
            oSegmReq.segmentIdx = this.segments.length;
            oSegmReq.owner = this;
            /* (end of custom properties) */
            oSegmReq.onload = pushSegment;
            this.segments.push("Content-Disposition: form-data; name=\"" + oField.name + "\"; filename=\""+ oFile.name + "\"\r\nContent-Type: " + oFile.type + "\r\n\r\n");
            this.status++;
            oSegmReq.readAsBinaryString(oFile);
          }
        } else {
          /* enctype is application/x-www-form-urlencoded or text/plain or method is GET: files will not be sent! */
          for (nFile = 0; nFile < oField.files.length; this.segments.push(fFilter(oField.name) + "=" + fFilter(oField.files[nFile++].name)));
        }
      } else if ((sFieldType !== "RADIO" && sFieldType !== "CHECKBOX") || oField.checked) {
        /* field type is not FILE or is FILE but is empty */
        this.segments.push(
          this.technique === 3 ? /* enctype is multipart/form-data */
            "Content-Disposition: form-data; name=\"" + oField.name + "\"\r\n\r\n" + oField.value + "\r\n"
          : /* enctype is application/x-www-form-urlencoded or text/plain or method is GET */
            fFilter(oField.name) + "=" + fFilter(oField.value)
        );
      }
    }
    processStatus(this);
  }

  return function (oFormElement) {
    if (!oFormElement.action) { return; }
    new SubmitRequest(oFormElement);
  };

})();

</script>
</head>
<body>

<h1>Sending forms with pure AJAX</h1>

<h2>Using the GET method</h2>

<form action="register.php" method="get" onsubmit="AJAXSubmit(this); return false;">
  <fieldset>
    <legend>Registration example</legend>
    <p>
      First name: <input type="text" name="firstname" /><br />
      Last name: <input type="text" name="lastname" />
    </p>
    <p>
      <input type="submit" value="Submit" />
    </p>
  </fieldset>
</form>

<h2>Using the POST method</h2>
<h3>Enctype: application/x-www-form-urlencoded (default)</h3>

<form action="register.php" method="post" onsubmit="AJAXSubmit(this); return false;">
  <fieldset>
    <legend>Registration example</legend>
    <p>
      First name: <input type="text" name="firstname" /><br />
      Last name: <input type="text" name="lastname" />
    </p>
    <p>
      <input type="submit" value="Submit" />
    </p>
  </fieldset>
</form>

<h3>Enctype: text/plain</h3>

<form action="register.php" method="post" enctype="text/plain" onsubmit="AJAXSubmit(this); return false;">
  <fieldset>
    <legend>Registration example</legend>
    <p>
      Your name: <input type="text" name="user" />
    </p>
    <p>
      Your message:<br />
      <textarea name="message" cols="40" rows="8"></textarea>
    </p>
    <p>
      <input type="submit" value="Submit" />
    </p>
  </fieldset>
</form>

<h3>Enctype: multipart/form-data</h3>

<form action="register.php" method="post" enctype="multipart/form-data" onsubmit="AJAXSubmit(this); return false;">
  <fieldset>
    <legend>Upload example</legend>
    <p>
      First name: <input type="text" name="firstname" /><br />
      Last name: <input type="text" name="lastname" /><br />
      Sex:
      <input id="sex_male" type="radio" name="sex" value="male" /> <label for="sex_male">Male</label>
      <input id="sex_female" type="radio" name="sex" value="female" /> <label for="sex_female">Female</label><br />
      Password: <input type="password" name="secret" /><br />
      What do you prefer:
      <select name="image_type">
        <option>Books</option>
        <option>Cinema</option>
        <option>TV</option>
      </select>
    </p>
    <p>
      Post your photos:
      <input type="file" multiple name="photos[]">
    </p>
    <p>
      <input id="vehicle_bike" type="checkbox" name="vehicle[]" value="Bike" /> <label for="vehicle_bike">I have a bike</label><br />
      <input id="vehicle_car" type="checkbox" name="vehicle[]" value="Car" /> <label for="vehicle_car">I have a car</label>
    </p>
    <p>
      Describe yourself:<br />
      <textarea name="description" cols="50" rows="8"></textarea>
    </p>
    <p>
      <input type="submit" value="Submit" />
    </p>
  </fieldset>
</form>

</body>
</html>

To test it, please, create a page named register.php (which is the action attribute of these sample forms) and just put the following minimalistic content:

<?php

  /* register.php */

  header("Content-type: text/plain");

  echo ":: data received via GET ::\n\n";
  print_r($_GET);

  echo "\n\n:: Data received via POST ::\n\n";
  print_r($_POST);

  echo "\n\n:: Data received as \"raw\" (text/plain encoding) ::\n\n";
  if (isset($HTTP_RAW_POST_DATA)) { echo $HTTP_RAW_POST_DATA; }

  echo "\n\n:: Files received ::\n\n";
  print_r($_FILES);

?>

The syntax of this script is the following:

AJAXSubmit(myForm);
Note: This little vanilla framework uses the FileReader API, which is a recent technique (but only when there are files to upload, the method of the {{ HTMLElement("form") }} is POST and the enctype attribute is setted to multipart/form-data). For this reason, the pure-AJAX upload is to be considered an experimental technique. Instead, if you don't want to upload files, this framework will not use any recent API.
Note also that the best way to send binary content is using ArrayBuffers or Blobs in conjuncton with the send() method and, possibly, with the readAsArrayBuffer() method of the FileReader API. But, since the aim of this little script is to work with a stringifiable raw data, we used the sendAsBinary() method in conjunction with the readAsBinaryString() method of the FileReader API. So, this is the best solution when working with a relatively few data which must be stringified in order to be reused later. Anyhow, since working with strings instead of typed arrays implies a greater waste of resources, this script makes sense only when you are dealing with small files (like images, documents, mp3, etc.). Otherwise, if you don't want to stringify the submitted or uploaded data, in addition to typed arrays, consider also the use of the FormData API.

Using FormData objects

The FormData constructor 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. For didactic purpose only we post here a translation of the previous example transformed so as to make use of the FormData API. Note the brevity of the code:

<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Sending forms with FormData &ndash; MDN</title>
<script type="text/javascript">
"use strict";

function ajaxSuccess () {
  alert(this.responseText);
}

function AJAXSubmit (oFormElement) {
  if (!oFormElement.action) { return; }
  var oReq = new XMLHttpRequest();
  oReq.onload = ajaxSuccess;
  if (oFormElement.method.toLowerCase() === "post") {
    oReq.open("post", oFormElement.action, true);
    oReq.send(new FormData(oFormElement));
  } else {
    var oField, sFieldType, nFile, sSearch = "";
    for (var nItem = 0; nItem < oFormElement.elements.length; nItem++) {
      oField = oFormElement.elements[nItem];
      if (!oField.hasAttribute("name")) { continue; }
      sFieldType = oField.nodeName.toUpperCase() === "INPUT" ? oField.getAttribute("type").toUpperCase() : "TEXT";
      if (sFieldType === "FILE") {
        for (nFile = 0; nFile < oField.files.length; sSearch += "&" + escape(oField.name) + "=" + escape(oField.files[nFile++].name));
      } else if ((sFieldType !== "RADIO" && sFieldType !== "CHECKBOX") || oField.checked) {
        sSearch += "&" + escape(oField.name) + "=" + escape(oField.value);
      }
    }
    oReq.open("get", oFormElement.action.replace(/(?:\?.*)?$/, sSearch.replace(/^&/, "?")), true);
    oReq.send(null);
  }
}
</script>
</head>
<body>

<h1>Sending forms with FormData</h1>

<h2>Using the GET method</h2>

<form action="register.php" method="get" onsubmit="AJAXSubmit(this); return false;">
  <fieldset>
    <legend>Registration example</legend>
    <p>
      First name: <input type="text" name="firstname" /><br />
      Last name: <input type="text" name="lastname" />
    </p>
    <p>
      <input type="submit" value="Submit" />
    </p>
  </fieldset>
</form>

<h2>Using the POST method</h2>
<h3>Enctype: application/x-www-form-urlencoded (default)</h3>

<form action="register.php" method="post" onsubmit="AJAXSubmit(this); return false;">
  <fieldset>
    <legend>Registration example</legend>
    <p>
      First name: <input type="text" name="firstname" /><br />
      Last name: <input type="text" name="lastname" />
    </p>
    <p>
      <input type="submit" value="Submit" />
    </p>
  </fieldset>
</form>

<h3>Enctype: text/plain</h3>

<p>The text/plain encoding is not supported by the FormData API.</p>

<h3>Enctype: multipart/form-data</h3>

<form action="register.php" method="post" enctype="multipart/form-data" onsubmit="AJAXSubmit(this); return false;">
  <fieldset>
    <legend>Upload example</legend>
    <p>
      First name: <input type="text" name="firstname" /><br />
      Last name: <input type="text" name="lastname" /><br />
      Sex:
      <input id="sex_male" type="radio" name="sex" value="male" /> <label for="sex_male">Male</label>
      <input id="sex_female" type="radio" name="sex" value="female" /> <label for="sex_female">Female</label><br />
      Password: <input type="password" name="secret" /><br />
      What do you prefer:
      <select name="image_type">
        <option>Books</option>
        <option>Cinema</option>
        <option>TV</option>
      </select>
    </p>
    <p>
      Post your photos:
      <input type="file" multiple name="photos[]">
    </p>
    <p>
      <input id="vehicle_bike" type="checkbox" name="vehicle[]" value="Bike" /> <label for="vehicle_bike">I have a bike</label><br />
      <input id="vehicle_car" type="checkbox" name="vehicle[]" value="Car" /> <label for="vehicle_car">I have a car</label>
    </p>
    <p>
      Describe yourself:<br />
      <textarea name="description" cols="50" rows="8"></textarea>
    </p>
    <p>
      <input type="submit" value="Submit" />
    </p>
  </fieldset>
</form>

</body>
</html>
Note: As we said, FormData objects are not stringifiable objects. If you want to stringify a submitted data, use the previous pure-AJAX example. Note also that, although in this example there are some file {{ HTMLElement("input") }} fields, when you submit a form through the FormData API you do not need to use the FileReader API also: files are automatically loaded and uploaded.

Get last modified date

function getHeaderTime () {
  alert(this.getResponseHeader("Last-Modified")); // A valid GMTString date or null
}

var oReq = XMLHttpRequest();
oReq.open("HEAD" /* use HEAD if you only need the headers! */, "yourpage.html", true);
oReq.onload = getHeaderTime;
oReq.send();

Do something when last modified date changes

Let's create these two functions:

function getHeaderTime () {
  var nLastVisit = parseFloat(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + escape(this.filepath).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")), nLastModif = Date.parse(this.getResponseHeader("Last-Modified"));

  if (isNaN(nLastVisit) || nLastModif > nLastVisit) {
    document.cookie = escape(this.filepath) + "=" + Date.now() + "; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=" + location.pathname;
    isFinite(nLastVisit) && this.callback();
  }
}

function whenPageChanges (sURL, fCallback) {
  var oReq = XMLHttpRequest();
  oReq.open("HEAD" /* use HEAD - we only need the headers! */, sURL, true);
  oReq.callback = fCallback;
  oReq.filepath = sURL;
  oReq.onload = getHeaderTime;
  oReq.send();
}

Test:

/* Let's test the file "yourpage.html"... */

whenPageChanges("yourpage.html", function () {
  alert("The page \"yourpage.html\" has been changed!");
});

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 oReq = new XMLHttpRequest();

oReq.open("GET", url + ((/\?/).test(url) ? "&" : "?") + (new Date()).getTime(), true);
oReq.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 oReq = 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 oReq = XMLHttpRequest();

See also

  1. MDN 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 <code>true</code> or not specified, the <code>XMLHttpRequest</code> is processed asynchronously, otherwise the process is handled synchronously. 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, you should rarely if ever use synchronous requests.</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="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 oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
// retrieve data unprocessed as a binary string
oReq.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 oReq = new XMLHttpRequest();

oReq.open("GET", url, true);
oReq.responseType = "arraybuffer";
oReq.onload = function(e) {
&nbsp; var arraybuffer = oReq.response; // not responseText
&nbsp; /* ... */
}
oReq.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>: these events implement the {{domxref("ProgressEvent")}} interface.</p>
<pre class="brush:js">
var oReq = new XMLHttpRequest();

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

oReq.open();

// ...

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

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 oReq = new XMLHttpRequest();

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

oReq.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="Submitting_forms_and_uploading_files">Submitting forms and uploading files</h2>
<p>Instances of <code>XMLHttpRequest</code> can be used to submit forms in two ways:</p>
<ul>
  <li>using nothing but <em>pure</em> AJAX,</li>
  <li>using the <a href="/en-US/docs/DOM/XMLHttpRequest/FormData" title="DOM/XMLHttpRequest/FormData"><code>FormData</code></a> API.</li>
</ul>
<p>The <strong>second way</strong> (using the <a href="/en-US/docs/DOM/XMLHttpRequest/FormData" title="DOM/XMLHttpRequest/FormData"><code>FormData</code></a> API) is the simplest and the fastest, but has the disadvantage that <strong>the data thus collected can not be <a href="/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify" title="/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify">stringified</a></strong>: they are in every way <em>a blob</em>. It is the best solution for simple cases.<br />
  The <strong>first way</strong> (<em>pure</em> AJAX) is instead the most complex, but in compensation is also the most flexible and powerful: it lends itself to wider uses and <strong>the data thus collected can be <a href="/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify" title="/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify">stringified</a></strong><strong> and reused for other purposes</strong> such as, for example, populating the <em>status object</em> during a <a href="/en-US/docs/DOM/Manipulating_the_browser_history" title="/en-US/docs/DOM/Manipulating_the_browser_history">manipulation of the browser history</a>, or other.</p>
<h3 id="Using_nothing_but_pure_AJAX">Using nothing but <em>pure</em> AJAX</h3>
<p>Submitting forms without the <a href="/en-US/docs/DOM/XMLHttpRequest/FormData" title="DOM/XMLHttpRequest/FormData"><code>FormData</code></a> API does not require other APIs, except that, only <strong>if you want to upload one or more files</strong>, the <a href="/en-US/docs/DOM/FileReader" title="/en-US/docs/DOM/FileReader"><code>FileReader</code></a> API.</p>
<h4 id="A_brief_introduction_to_the_submit_methods">A brief introduction to the submit methods</h4>
<p>An html {{ HTMLElement("form") }} can be sent in four ways:</p>
<ul>
  <li>using the <code>POST</code> method and setting the <code>enctype</code> attribute to <code>application/x-www-form-urlencoded</code> (default);</li>
  <li>using the <code>POST</code> method and setting the <code>enctype</code> attribute to <code>text/plain</code>;</li>
  <li>using the <code>POST</code> method and setting the <code>enctype</code> attribute to <code>multipart/form-data</code>;</li>
  <li>using the <code>GET</code> method (in this case the <code>enctype</code> attribute will be ignored).</li>
</ul>
<p>Now, consider to submit a form containing only two fields, named <code>foo</code> and <code>baz</code>. If you are using the <code>POST</code> method, the server will receive a string similar to one of the following three ones depending on the encoding type you are using:</p>
<ul>
  <li>
    <p>Method: <code>POST</code>; Encoding type: <code>application/x-www-form-urlencoded</code> (default):</p>
    <pre>
Content-Type: application/x-www-form-urlencoded

foo=bar&amp;baz=The+first+line.&amp;#37;0D%0AThe+second+line.%0D%0A</pre>
  </li>
  <li>
    <p>Method: <code>POST</code>; Encoding type: <code>text/plain</code>:</p>
    <pre>
Content-Type: text/plain

foo=bar
baz=The first line.
The second line.</pre>
  </li>
  <li>
    <p>Method: <code>POST</code>; Encoding type: <code>multipart/form-data</code>:</p>
    <pre style="height: 100px; overflow: auto;">
Content-Type: multipart/form-data; boundary=---------------------------314911788813839

-----------------------------314911788813839
Content-Disposition: form-data; name="foo"

bar
-----------------------------314911788813839
Content-Disposition: form-data; name="baz"

The first line.
The second line.

-----------------------------314911788813839--</pre>
  </li>
</ul>
<p>Instead, if you are using the <code>GET</code> method, a string like the following will be simply added to the URL:</p>
<pre>
?foo=bar&amp;baz=The%20first%20line.%0AThe%20second%20line.</pre>
<h4 id="A_little_vanilla_framework">A little <em>vanilla</em> framework</h4>
<p>All these things are done automatically by the web browser whenever you submit a {{ HTMLElement("form") }}. But if you want to do the same things using JavaScript you have to instruct the interpreter about <em>all</em> things. So, how to send forms in <em>pure</em> AJAX is too complex to be explained in detail here. For this reason we posted here <strong>a complete (but still didactic) framework</strong>, which is able to use all the four ways of <em>submit</em> and, also, to <strong>upload files</strong>:</p>
<div style="height: 400px; margin-bottom: 12px; overflow: auto;">
  <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;Sending forms with pure AJAX &amp;ndash; MDN&lt;/title&gt;
&lt;script type="text/javascript"&gt;

"use strict";

/*\
|*|
|*|&nbsp; :: XMLHttpRequest.prototype.sendAsBinary() Polifyll ::
|*|
|*|&nbsp; https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#sendAsBinary()
\*/

if (!XMLHttpRequest.prototype.sendAsBinary) {
&nbsp; XMLHttpRequest.prototype.sendAsBinary = function (sData) {
&nbsp;&nbsp;&nbsp; var nBytes = sData.length, ui8Data = new Uint8Array(nBytes);
&nbsp;&nbsp;&nbsp; for (var nIdx = 0; nIdx &lt; nBytes; nIdx++) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ui8Data[nIdx] = sData.charCodeAt(nIdx) &amp; 0xff;
&nbsp;&nbsp;&nbsp; }
&nbsp;&nbsp;&nbsp; /* send as ArrayBufferView...: */
    this.send(ui8Data);
&nbsp;&nbsp;&nbsp; /* ...or as ArrayBuffer (legacy)...: this.send(ui8Data.buffer); */
&nbsp; };
}

/*\
|*|
|*|&nbsp; :: AJAX Form Submit Framework ::
|*|
|*|&nbsp; https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest
|*|
|*|  This framework is released under the GNU Public License, version 3 or later.
|*|&nbsp; http://www.gnu.org/licenses/gpl-3.0-standalone.html
|*|
|*|&nbsp; Syntax:
|*|
|*|&nbsp;&nbsp; AJAXSubmit(HTMLFormElement);
\*/

var AJAXSubmit = (function () {

&nbsp; function ajaxSuccess () {
&nbsp;&nbsp;&nbsp; /* console.log("AJAXSubmit - Success!"); */
&nbsp;&nbsp;&nbsp; alert(this.responseText);
&nbsp;&nbsp;&nbsp; /* you can get the serialized data through the "submittedData" custom property: */
&nbsp;&nbsp;&nbsp; /* alert(JSON.stringify(this.submittedData)); */
&nbsp; }

&nbsp; function submitData (oData) {
&nbsp;&nbsp;&nbsp; /* the AJAX request... */
&nbsp;&nbsp;&nbsp; var oAjaxReq = new XMLHttpRequest();
&nbsp;&nbsp;&nbsp; oAjaxReq.submittedData = oData;
&nbsp;&nbsp;&nbsp; oAjaxReq.onload = ajaxSuccess;
&nbsp;&nbsp;&nbsp; if (oData.technique === 0) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; /* method is GET */
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; oAjaxReq.open("get", oData.receiver.replace(/(?:\?.*)?$/, oData.segments.length &gt; 0 ? "?" + oData.segments.join("&amp;") : ""), true);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; oAjaxReq.send(null);
&nbsp;&nbsp;&nbsp; } else {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; /* method is POST */
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; oAjaxReq.open("post", oData.receiver, true);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (oData.technique === 3) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; /* enctype is multipart/form-data */
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; var sBoundary = "---------------------------" + Date.now().toString(16);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; oAjaxReq.setRequestHeader("Content-Type", "multipart\/form-data; boundary=" + sBoundary);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; oAjaxReq.sendAsBinary("--" + sBoundary + "\r\n" + oData.segments.join("--" + sBoundary + "\r\n") + "--" + sBoundary + "--\r\n");
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; } else {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; /* enctype is application/x-www-form-urlencoded or text/plain */
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; oAjaxReq.setRequestHeader("Content-Type", oData.contentType);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; oAjaxReq.send(oData.segments.join(oData.technique === 2 ? "\r\n" : "&amp;"));
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }
&nbsp;&nbsp;&nbsp; }
&nbsp; }

&nbsp; function processStatus (oData) {
&nbsp;&nbsp;&nbsp; if (oData.status &gt; 0) { return; }
&nbsp;&nbsp;&nbsp; /* the form is now totally serialized! do something before sending it to the server... */
&nbsp;&nbsp;&nbsp; /* doSomething(oData); */
&nbsp;&nbsp;&nbsp; /* console.log("AJAXSubmit - The form is now serialized. Submitting..."); */
&nbsp;&nbsp;&nbsp; submitData (oData);
&nbsp; }

&nbsp; function pushSegment (oFREvt) {
&nbsp;&nbsp;&nbsp; this.owner.segments[this.segmentIdx] += oFREvt.target.result + "\r\n";
&nbsp;&nbsp;&nbsp; this.owner.status--;
&nbsp;&nbsp;&nbsp; processStatus(this.owner);
&nbsp; }

&nbsp; function plainEscape (sText) {
&nbsp;&nbsp;&nbsp; /* how should I treat a text/plain form encoding? what characters are not allowed? this is what I suppose...: */
&nbsp;&nbsp;&nbsp; /* "4\3\7 - Einstein said E=mc2" ----&gt; "4\\3\\7\ -\ Einstein\ said\ E\=mc2" */
&nbsp;&nbsp;&nbsp; return sText.replace(/[\s\=\\]/g, "\\$&amp;");
&nbsp; }

&nbsp; function SubmitRequest (oTarget) {
&nbsp;&nbsp;&nbsp; var nFile, sFieldType, oField, oSegmReq, oFile, bIsPost = oTarget.method.toLowerCase() === "post";
&nbsp;&nbsp;&nbsp; /* console.log("AJAXSubmit - Serializing form..."); */
&nbsp;&nbsp;&nbsp; this.contentType = bIsPost &amp;&amp; oTarget.enctype ? oTarget.enctype : "application\/x-www-form-urlencoded";
&nbsp;&nbsp;&nbsp; this.technique = bIsPost ? this.contentType === "multipart\/form-data" ? 3 : this.contentType === "text\/plain" ? 2 : 1 : 0;
&nbsp;&nbsp;&nbsp; this.receiver = oTarget.action;
&nbsp;&nbsp;&nbsp; this.status = 0;
&nbsp;&nbsp;&nbsp; this.segments = [];
&nbsp;&nbsp;&nbsp; var fFilter = this.technique === 2 ? plainEscape : escape;
&nbsp;&nbsp;&nbsp; for (var nItem = 0; nItem &lt; oTarget.elements.length; nItem++) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; oField = oTarget.elements[nItem];
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (!oField.hasAttribute("name")) { continue; }
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; sFieldType = oField.nodeName.toUpperCase() === "INPUT" ? oField.getAttribute("type").toUpperCase() : "TEXT";
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (sFieldType === "FILE" &amp;&amp; oField.files.length &gt; 0) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (this.technique === 3) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; /* enctype is multipart/form-data */
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; for (nFile = 0; nFile &lt; oField.files.length; nFile++) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; oFile = oField.files[nFile];
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; oSegmReq = new FileReader();
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; /* (custom properties:) */
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; oSegmReq.segmentIdx = this.segments.length;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; oSegmReq.owner = this;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; /* (end of custom properties) */
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; oSegmReq.onload = pushSegment;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; this.segments.push("Content-Disposition: form-data; name=\"" + oField.name + "\"; filename=\""+ oFile.name + "\"\r\nContent-Type: " + oFile.type + "\r\n\r\n");
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; this.status++;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; oSegmReq.readAsBinaryString(oFile);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; } else {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; /* enctype is application/x-www-form-urlencoded or text/plain or method is GET: files will not be sent! */
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; for (nFile = 0; nFile &lt; oField.files.length; this.segments.push(fFilter(oField.name) + "=" + fFilter(oField.files[nFile++].name)));
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; } else if ((sFieldType !== "RADIO" &amp;&amp; sFieldType !== "CHECKBOX") || oField.checked) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; /* field type is not FILE or is FILE but is empty */
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; this.segments.push(
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; this.technique === 3 ? /* enctype is multipart/form-data */
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "Content-Disposition: form-data; name=\"" + oField.name + "\"\r\n\r\n" + oField.value + "\r\n"
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; : /* enctype is application/x-www-form-urlencoded or text/plain or method is GET */
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; fFilter(oField.name) + "=" + fFilter(oField.value)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; );
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }
&nbsp;&nbsp;&nbsp; }
&nbsp;&nbsp;&nbsp; processStatus(this);
&nbsp; }

&nbsp; return function (oFormElement) {
&nbsp;&nbsp;&nbsp; if (!oFormElement.action) { return; }
&nbsp;&nbsp;&nbsp; new SubmitRequest(oFormElement);
&nbsp; };

})();

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

&lt;h1&gt;Sending forms with pure AJAX&lt;/h1&gt;

&lt;h2&gt;Using the GET method&lt;/h2&gt;

&lt;form action="register.php" method="get" onsubmit="AJAXSubmit(this); return false;"&gt;
&nbsp; &lt;fieldset&gt;
&nbsp;&nbsp;&nbsp; &lt;legend&gt;Registration example&lt;/legend&gt;
&nbsp;&nbsp;&nbsp; &lt;p&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; First name: &lt;input type="text" name="firstname" /&gt;&lt;br /&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Last name: &lt;input type="text" name="lastname" /&gt;
&nbsp;&nbsp;&nbsp; &lt;/p&gt;
&nbsp;&nbsp;&nbsp; &lt;p&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;input type="submit" value="Submit" /&gt;
&nbsp;&nbsp;&nbsp; &lt;/p&gt;
&nbsp; &lt;/fieldset&gt;
&lt;/form&gt;

&lt;h2&gt;Using the POST method&lt;/h2&gt;
&lt;h3&gt;Enctype: application/x-www-form-urlencoded (default)&lt;/h3&gt;

&lt;form action="register.php" method="post" onsubmit="AJAXSubmit(this); return false;"&gt;
&nbsp; &lt;fieldset&gt;
&nbsp;&nbsp;&nbsp; &lt;legend&gt;Registration example&lt;/legend&gt;
&nbsp;&nbsp;&nbsp; &lt;p&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; First name: &lt;input type="text" name="firstname" /&gt;&lt;br /&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Last name: &lt;input type="text" name="lastname" /&gt;
&nbsp;&nbsp;&nbsp; &lt;/p&gt;
&nbsp;&nbsp;&nbsp; &lt;p&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;input type="submit" value="Submit" /&gt;
&nbsp;&nbsp;&nbsp; &lt;/p&gt;
&nbsp; &lt;/fieldset&gt;
&lt;/form&gt;

&lt;h3&gt;Enctype: text/plain&lt;/h3&gt;

&lt;form action="register.php" method="post" enctype="text/plain" onsubmit="AJAXSubmit(this); return false;"&gt;
&nbsp; &lt;fieldset&gt;
&nbsp;&nbsp;&nbsp; &lt;legend&gt;Registration example&lt;/legend&gt;
&nbsp;&nbsp;&nbsp; &lt;p&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Your name: &lt;input type="text" name="user" /&gt;
&nbsp;&nbsp;&nbsp; &lt;/p&gt;
&nbsp;&nbsp;&nbsp; &lt;p&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Your message:&lt;br /&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;textarea name="message" cols="40" rows="8"&gt;&lt;/textarea&gt;
&nbsp;&nbsp;&nbsp; &lt;/p&gt;
&nbsp;&nbsp;&nbsp; &lt;p&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;input type="submit" value="Submit" /&gt;
&nbsp;&nbsp;&nbsp; &lt;/p&gt;
&nbsp; &lt;/fieldset&gt;
&lt;/form&gt;

&lt;h3&gt;Enctype: multipart/form-data&lt;/h3&gt;

&lt;form action="register.php" method="post" enctype="multipart/form-data" onsubmit="AJAXSubmit(this); return false;"&gt;
&nbsp; &lt;fieldset&gt;
&nbsp;&nbsp;&nbsp; &lt;legend&gt;Upload example&lt;/legend&gt;
&nbsp;&nbsp;&nbsp; &lt;p&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; First name: &lt;input type="text" name="firstname" /&gt;&lt;br /&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Last name: &lt;input type="text" name="lastname" /&gt;&lt;br /&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Sex:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;input id="sex_male" type="radio" name="sex" value="male" /&gt; &lt;label for="sex_male"&gt;Male&lt;/label&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;input id="sex_female" type="radio" name="sex" value="female" /&gt; &lt;label for="sex_female"&gt;Female&lt;/label&gt;&lt;br /&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Password: &lt;input type="password" name="secret" /&gt;&lt;br /&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; What do you prefer:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;select name="image_type"&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;option&gt;Books&lt;/option&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;option&gt;Cinema&lt;/option&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;option&gt;TV&lt;/option&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;/select&gt;
&nbsp;&nbsp;&nbsp; &lt;/p&gt;
&nbsp;&nbsp;&nbsp; &lt;p&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Post your photos:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;input type="file" multiple name="photos[]"&gt;
&nbsp;&nbsp;&nbsp; &lt;/p&gt;
&nbsp;&nbsp;&nbsp; &lt;p&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;input id="vehicle_bike" type="checkbox" name="vehicle[]" value="Bike" /&gt; &lt;label for="vehicle_bike"&gt;I have a bike&lt;/label&gt;&lt;br /&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;input id="vehicle_car" type="checkbox" name="vehicle[]" value="Car" /&gt; &lt;label for="vehicle_car"&gt;I have a car&lt;/label&gt;
&nbsp;&nbsp;&nbsp; &lt;/p&gt;
&nbsp;&nbsp;&nbsp; &lt;p&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Describe yourself:&lt;br /&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;textarea name="description" cols="50" rows="8"&gt;&lt;/textarea&gt;
&nbsp;&nbsp;&nbsp; &lt;/p&gt;
&nbsp;&nbsp;&nbsp; &lt;p&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;input type="submit" value="Submit" /&gt;
&nbsp;&nbsp;&nbsp; &lt;/p&gt;
&nbsp; &lt;/fieldset&gt;
&lt;/form&gt;

&lt;/body&gt;
&lt;/html&gt;</pre>
</div>
<p>To test it, please, create a<span class="long_text short_text" id="result_box" lang="en"><span class="hps"> </span></span>page named <strong>register.php</strong> (which is the <code>action</code> attribute of these sample forms) and just put the following <em><span class="long_text short_text" id="result_box" lang="en"><span class="hps">minimalistic </span></span></em>content:</p>
<pre class="brush: php">
&lt;?php

&nbsp; /* register.php */

&nbsp; header("Content-type: text/plain");

&nbsp; echo ":: data received via GET ::\n\n";
&nbsp; print_r($_GET);

&nbsp; echo "\n\n:: Data received via POST ::\n\n";
&nbsp; print_r($_POST);

&nbsp; echo "\n\n:: Data received as \"raw\" (text/plain encoding) ::\n\n";
&nbsp; if (isset($HTTP_RAW_POST_DATA)) { echo $HTTP_RAW_POST_DATA; }

&nbsp; echo "\n\n:: Files received ::\n\n";
&nbsp; print_r($_FILES);

?&gt;</pre>
<p>The syntax of this script is the following:</p>
<pre class="syntaxbox">
AJAXSubmit(myForm);</pre>
<div class="note">
  <strong>Note:</strong> This little <em>vanilla</em> framework <strong>uses the <a href="/en-US/docs/DOM/FileReader" title="/en-US/docs/DOM/FileReader"><code>FileReader</code></a> API</strong>, which is <em>a recent technique</em> (but only when there are files to upload, the <code>method</code> of the {{ HTMLElement("form") }} is <code>POST</code> and the <code>enctype</code> attribute is setted to <code>multipart/form-data</code>). For this reason, <strong>the <em>pure-AJAX</em> upload is to be considered an experimental technique</strong>. Instead, if you don't want to upload files, this framework will not use any recent API.<br />
  Note also that <strong>the best way to send binary content is using <a href="/en-US/docs/JavaScript/Typed_arrays/ArrayBuffer" title="/en-US/docs/JavaScript/Typed_arrays/ArrayBuffer">ArrayBuffers</a> or <a href="/en-US/docs/DOM/Blob" title="/en-US/docs/DOM/Blob">Blobs</a> in conjuncton with the <a href="/en-US/docs/DOM/XMLHttpRequest#send%28%29" title="/en-US/docs/DOM/XMLHttpRequest#send()"><code>send()</code></a> method and, possibly, with the <a href="/en-US/docs/DOM/FileReader#readAsArrayBuffer()" title="/en-US/docs/DOM/FileReader#readAsArrayBuffer()"><code>readAsArrayBuffer()</code></a> method of the <a href="/en-US/docs/DOM/FileReader" title="/en-US/docs/DOM/FileReader"><code>FileReader</code></a> API</strong>. But, since the aim of this little script is to work with a <em><a href="/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify" title="/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify">stringifiable</a></em> raw data, we used the <a href="/en-US/docs/DOM/XMLHttpRequest#sendAsBinary%28%29" title="/en-US/docs/DOM/XMLHttpRequest#sendAsBinary()"><code>sendAsBinary()</code></a> method in conjunction with the <a href="/en-US/docs/DOM/FileReader#readAsBinaryString%28%29" title="/en-US/docs/DOM/FileReader#readAsBinaryString()"><code>readAsBinaryString()</code></a> method of the <a href="/en-US/docs/DOM/FileReader" title="/en-US/docs/DOM/FileReader"><code>FileReader</code></a> API. So, this is <strong>the best solution when working with a relatively few data which must be <a href="/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify" title="/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify">stringified</a> in order to be reused later</strong>. Anyhow, since working with strings instead of <a href="/en-US/docs/JavaScript/Typed_arrays" title="/en-US/docs/JavaScript/Typed_arrays">typed arrays</a> implies a greater waste of resources, this script makes sense only when you are dealing with <em>small</em> files (like images, documents, mp3, etc.). Otherwise, if you don't want to stringify the submitted or uploaded data, in addition to <a href="/en-US/docs/JavaScript/Typed_arrays" title="/en-US/docs/JavaScript/Typed_arrays">typed arrays</a>, consider also the use of <strong>the <a href="/en-US/docs/DOM/XMLHttpRequest/FormData" title="DOM/XMLHttpRequest/FormData"><code>FormData</code></a> API</strong>.</div>
<h3 id="Using_FormData_objects">Using FormData objects</h3>
<p>The <a href="/en-US/docs/DOM/XMLHttpRequest/FormData" title="DOM/XMLHttpRequest/FormData"><code>FormData</code></a> constructor 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. For didactic purpose only we post here <strong>a <em>translation</em> of <a href="#A_little_vanilla_framework" title="#A_little_vanilla_framework">the previous example</a> transformed so as to make use of the <code>FormData</code> API</strong>. Note the brevity of the code:</p>
<div style="height: 400px; margin-bottom: 12px; overflow: auto;">
  <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;Sending forms with FormData &amp;ndash; MDN&lt;/title&gt;
&lt;script type="text/javascript"&gt;
"use strict";

function ajaxSuccess () {
&nbsp; alert(this.responseText);
}

function AJAXSubmit (oFormElement) {
&nbsp; if (!oFormElement.action) { return; }
&nbsp; var oReq = new XMLHttpRequest();
&nbsp; oReq.onload = ajaxSuccess;
&nbsp; if (oFormElement.method.toLowerCase() === "post") {
&nbsp;&nbsp;&nbsp; oReq.open("post", oFormElement.action, true);
&nbsp;&nbsp;&nbsp; oReq.send(new FormData(oFormElement));
&nbsp; } else {
&nbsp;&nbsp;&nbsp; var oField, sFieldType, nFile, sSearch = "";
&nbsp;&nbsp;&nbsp; for (var nItem = 0; nItem &lt; oFormElement.elements.length; nItem++) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; oField = oFormElement.elements[nItem];
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (!oField.hasAttribute("name")) { continue; }
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; sFieldType = oField.nodeName.toUpperCase() === "INPUT" ? oField.getAttribute("type").toUpperCase() : "TEXT";
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (sFieldType === "FILE") {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; for (nFile = 0; nFile &lt; oField.files.length; sSearch += "&amp;" + escape(oField.name) + "=" + escape(oField.files[nFile++].name));
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; } else if ((sFieldType !== "RADIO" &amp;&amp; sFieldType !== "CHECKBOX") || oField.checked) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; sSearch += "&amp;" + escape(oField.name) + "=" + escape(oField.value);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }
&nbsp;&nbsp;&nbsp; }
&nbsp;&nbsp;&nbsp; oReq.open("get", oFormElement.action.replace(/(?:\?.*)?$/, sSearch.replace(/^&amp;/, "?")), true);
&nbsp;&nbsp;&nbsp; oReq.send(null);
&nbsp; }
}
&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;

&lt;h1&gt;Sending forms with FormData&lt;/h1&gt;

&lt;h2&gt;Using the GET method&lt;/h2&gt;

&lt;form action="register.php" method="get" onsubmit="AJAXSubmit(this); return false;"&gt;
&nbsp; &lt;fieldset&gt;
&nbsp;&nbsp;&nbsp; &lt;legend&gt;Registration example&lt;/legend&gt;
&nbsp;&nbsp;&nbsp; &lt;p&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; First name: &lt;input type="text" name="firstname" /&gt;&lt;br /&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Last name: &lt;input type="text" name="lastname" /&gt;
&nbsp;&nbsp;&nbsp; &lt;/p&gt;
&nbsp;&nbsp;&nbsp; &lt;p&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;input type="submit" value="Submit" /&gt;
&nbsp;&nbsp;&nbsp; &lt;/p&gt;
&nbsp; &lt;/fieldset&gt;
&lt;/form&gt;

&lt;h2&gt;Using the POST method&lt;/h2&gt;
&lt;h3&gt;Enctype: application/x-www-form-urlencoded (default)&lt;/h3&gt;

&lt;form action="register.php" method="post" onsubmit="AJAXSubmit(this); return false;"&gt;
&nbsp; &lt;fieldset&gt;
&nbsp;&nbsp;&nbsp; &lt;legend&gt;Registration example&lt;/legend&gt;
&nbsp;&nbsp;&nbsp; &lt;p&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; First name: &lt;input type="text" name="firstname" /&gt;&lt;br /&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Last name: &lt;input type="text" name="lastname" /&gt;
&nbsp;&nbsp;&nbsp; &lt;/p&gt;
&nbsp;&nbsp;&nbsp; &lt;p&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;input type="submit" value="Submit" /&gt;
&nbsp;&nbsp;&nbsp; &lt;/p&gt;
&nbsp; &lt;/fieldset&gt;
&lt;/form&gt;

&lt;h3&gt;Enctype: text/plain&lt;/h3&gt;

&lt;p&gt;The text/plain encoding is not supported by the FormData API.&lt;/p&gt;

&lt;h3&gt;Enctype: multipart/form-data&lt;/h3&gt;

&lt;form action="register.php" method="post" enctype="multipart/form-data" onsubmit="AJAXSubmit(this); return false;"&gt;
&nbsp; &lt;fieldset&gt;
&nbsp;&nbsp;&nbsp; &lt;legend&gt;Upload example&lt;/legend&gt;
&nbsp;&nbsp;&nbsp; &lt;p&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; First name: &lt;input type="text" name="firstname" /&gt;&lt;br /&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Last name: &lt;input type="text" name="lastname" /&gt;&lt;br /&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Sex:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;input id="sex_male" type="radio" name="sex" value="male" /&gt; &lt;label for="sex_male"&gt;Male&lt;/label&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;input id="sex_female" type="radio" name="sex" value="female" /&gt; &lt;label for="sex_female"&gt;Female&lt;/label&gt;&lt;br /&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Password: &lt;input type="password" name="secret" /&gt;&lt;br /&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; What do you prefer:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;select name="image_type"&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;option&gt;Books&lt;/option&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;option&gt;Cinema&lt;/option&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;option&gt;TV&lt;/option&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;/select&gt;
&nbsp;&nbsp;&nbsp; &lt;/p&gt;
&nbsp;&nbsp;&nbsp; &lt;p&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Post your photos:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;input type="file" multiple name="photos[]"&gt;
&nbsp;&nbsp;&nbsp; &lt;/p&gt;
&nbsp;&nbsp;&nbsp; &lt;p&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;input id="vehicle_bike" type="checkbox" name="vehicle[]" value="Bike" /&gt; &lt;label for="vehicle_bike"&gt;I have a bike&lt;/label&gt;&lt;br /&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;input id="vehicle_car" type="checkbox" name="vehicle[]" value="Car" /&gt; &lt;label for="vehicle_car"&gt;I have a car&lt;/label&gt;
&nbsp;&nbsp;&nbsp; &lt;/p&gt;
&nbsp;&nbsp;&nbsp; &lt;p&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Describe yourself:&lt;br /&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;textarea name="description" cols="50" rows="8"&gt;&lt;/textarea&gt;
&nbsp;&nbsp;&nbsp; &lt;/p&gt;
&nbsp;&nbsp;&nbsp; &lt;p&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;input type="submit" value="Submit" /&gt;
&nbsp;&nbsp;&nbsp; &lt;/p&gt;
&nbsp; &lt;/fieldset&gt;
&lt;/form&gt;

&lt;/body&gt;
&lt;/html&gt;</pre>
</div>
<div class="note">
  <strong>Note:</strong> As we said, <strong><code>FormData</code> objects are not <a href="/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify" title="/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify">stringifiable</a> objects</strong>. If you want to stringify a submitted data, use <a href="#A_little_vanilla_framework" title="#A_little_vanilla_framework">the previous <em>pure</em>-AJAX example</a>. Note also that, although in this example there are some <code>file</code> {{ HTMLElement("input") }} fields, <strong>when you submit a form through the <code>FormData</code> API you do not need to use the <a href="/en-US/docs/DOM/FileReader" title="/en-US/docs/DOM/FileReader"><code>FileReader</code></a> API also</strong>: files are automatically loaded and uploaded.</div>
<h2>Get last modified date</h2>
<pre class="brush: js">
function getHeaderTime () {
&nbsp; alert(this.getResponseHeader("Last-Modified")); // A valid GMTString date or null
}

var oReq = XMLHttpRequest();
oReq.open("HEAD" /* use HEAD if you only need the headers! */, "yourpage.html", true);
oReq.onload = getHeaderTime;
oReq.send();</pre>
<h3>Do something when last modified date changes</h3>
<p>Let's create these two functions:</p>
<pre class="brush: js">
function getHeaderTime () {
&nbsp; var nLastVisit = parseFloat(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + escape(this.filepath).replace(/[\-\.\+\*]/g, "\\$&amp;") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")), nLastModif = Date.parse(this.getResponseHeader("Last-Modified"));

&nbsp; if (isNaN(nLastVisit) || nLastModif &gt; nLastVisit) {
&nbsp;&nbsp;&nbsp; document.cookie = escape(this.filepath) + "=" + Date.now() + "; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=" + location.pathname;
&nbsp;&nbsp;&nbsp; isFinite(nLastVisit) &amp;&amp; this.callback();
&nbsp; }
}

function whenPageChanges (sURL, fCallback) {
&nbsp; var oReq = XMLHttpRequest();
&nbsp; oReq.open("HEAD" /* use HEAD - we only need the headers! */, sURL, true);
&nbsp; oReq.callback = fCallback;
&nbsp; oReq.filepath = sURL;
&nbsp; oReq.onload = getHeaderTime;
&nbsp; oReq.send();
}</pre>
<p>Test:</p>
<pre class="brush: js">
/* Let's test the file "yourpage.html"... */

whenPageChanges("yourpage.html", function () {
&nbsp; alert("The page \"yourpage.html\" has been changed!");
});</pre>
<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 oReq = new XMLHttpRequest();

oReq.open("GET", url + ((/\?/).test(url) ? "&amp;" : "?") + (new Date()).getTime(), true);
oReq.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 oReq = 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 oReq = XMLHttpRequest();
</pre>
<h2 id="See_also">See also</h2>
<ol>
  <li><a href="/en-US/docs/AJAX/Getting_Started" title="AJAX/Getting_Started">MDN 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