From 95aca4b4d8fa62815d4bd412fff1a364f842814a Mon Sep 17 00:00:00 2001 From: Ryan Johnson Date: Thu, 29 Apr 2021 16:16:42 -0700 Subject: remove retired locales (#699) --- files/id/web/api/xmlhttprequest/index.html | 200 ------ .../xmlhttprequest/using_xmlhttprequest/index.html | 793 --------------------- 2 files changed, 993 deletions(-) delete mode 100644 files/id/web/api/xmlhttprequest/index.html delete mode 100644 files/id/web/api/xmlhttprequest/using_xmlhttprequest/index.html (limited to 'files/id/web/api/xmlhttprequest') diff --git a/files/id/web/api/xmlhttprequest/index.html b/files/id/web/api/xmlhttprequest/index.html deleted file mode 100644 index 87f02b9550..0000000000 --- a/files/id/web/api/xmlhttprequest/index.html +++ /dev/null @@ -1,200 +0,0 @@ ---- -title: XMLHttpRequest -slug: Web/API/XMLHttpRequest -tags: - - AJAX - - API - - Communication - - HTTP - - Interface - - NeedsTranslation - - Reference - - TopicStub - - Web - - XHR - - XMLHttpRequest -translation_of: Web/API/XMLHttpRequest ---- -
{{DefaultAPISidebar("XMLHttpRequest")}}
- -

Use XMLHttpRequest (XHR) objects to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing. XMLHttpRequest is used heavily in {{Glossary("AJAX")}} programming.

- -

{{InheritanceDiagram(650, 150)}}

- -

Despite its name, XMLHttpRequest can be used to retrieve any type of data, not just XML.

- -

If your communication needs to involve receiving event data or message data from a server, consider using server-sent events through the {{domxref("EventSource")}} interface. For full-duplex communication, WebSockets may be a better choice.

- -

Constructor

- -
-
{{domxref("XMLHttpRequest.XMLHttpRequest", "XMLHttpRequest()")}}
-
The constructor initializes an XMLHttpRequest. It must be called before any other method calls.
-
- -

Properties

- -

This interface also inherits properties of {{domxref("XMLHttpRequestEventTarget")}} and of {{domxref("EventTarget")}}.

- -
-
{{domxref("XMLHttpRequest.onreadystatechange")}}
-
An {{domxref("EventHandler")}} that is called whenever the readyState attribute changes.
-
{{domxref("XMLHttpRequest.readyState")}} {{readonlyinline}}
-
Returns an unsigned short, the state of the request.
-
{{domxref("XMLHttpRequest.response")}} {{readonlyinline}}
-
Returns an {{jsxref("ArrayBuffer")}}, {{domxref("Blob")}}, {{domxref("Document")}}, JavaScript object, or a {{domxref("DOMString")}}, depending on the value of {{domxref("XMLHttpRequest.responseType")}}, that contains the response entity body.
-
{{domxref("XMLHttpRequest.responseText")}} {{readonlyinline}}
-
Returns a {{domxref("DOMString")}} that contains the response to the request as text, or null if the request was unsuccessful or has not yet been sent.
-
{{domxref("XMLHttpRequest.responseType")}}
-
Is an enumerated value that defines the response type.
-
{{domxref("XMLHttpRequest.responseURL")}} {{readonlyinline}}
-
Returns the serialized URL of the response or the empty string if the URL is null.
-
{{domxref("XMLHttpRequest.responseXML")}} {{readonlyinline}}
-
Returns a {{domxref("Document")}} containing the response to the request, or null if the request was unsuccessful, has not yet been sent, or cannot be parsed as XML or HTML. Not available in workers.
-
{{domxref("XMLHttpRequest.status")}} {{readonlyinline}}
-
Returns an unsigned short with the status of the response of the request.
-
{{domxref("XMLHttpRequest.statusText")}} {{readonlyinline}}
-
Returns a {{domxref("DOMString")}} containing the response string returned by the HTTP server. Unlike {{domxref("XMLHttpRequest.status")}}, this includes the entire text of the response message ("200 OK", for example).
-
- -
-

Note: According to the HTTP/2 specification (8.1.2.4 Response Pseudo-Header Fields), HTTP/2 does not define a way to carry the version or reason phrase that is included in an HTTP/1.1 status line.

-
- -
-
{{domxref("XMLHttpRequest.timeout")}}
-
Is an unsigned long representing the number of milliseconds a request can take before automatically being terminated.
-
{{domxref("XMLHttpRequestEventTarget.ontimeout")}}
-
Is an {{domxref("EventHandler")}} that is called whenever the request times out. {{gecko_minversion_inline("12.0")}}
-
{{domxref("XMLHttpRequest.upload")}} {{readonlyinline}}
-
Is an {{domxref("XMLHttpRequestUpload")}}, representing the upload process.
-
{{domxref("XMLHttpRequest.withCredentials")}}
-
Is a {{domxref("Boolean")}} that indicates whether or not cross-site Access-Control requests should be made using credentials such as cookies or authorization headers.
-
- -

Non-standard properties

- -
-
{{domxref("XMLHttpRequest.channel")}}{{ReadOnlyInline}}
-
Is a {{Interface("nsIChannel")}}. The channel used by the object when performing the request.
-
{{domxref("XMLHttpRequest.mozAnon")}}{{ReadOnlyInline}}
-
Is a boolean. If true, the request will be sent without cookie and authentication headers.
-
{{domxref("XMLHttpRequest.mozSystem")}}{{ReadOnlyInline}}
-
Is a boolean. If true, the same origin policy will not be enforced on the request.
-
{{domxref("XMLHttpRequest.mozBackgroundRequest")}}
-
Is a boolean. It indicates whether or not the object represents a background service request.
-
{{domxref("XMLHttpRequest.mozResponseArrayBuffer")}}{{gecko_minversion_inline("2.0")}} {{obsolete_inline("6")}} {{ReadOnlyInline}}
-
{{jsxref("ArrayBuffer")}}. The response to the request, as a JavaScript typed array.
-
{{domxref("XMLHttpRequest.multipart")}}{{obsolete_inline("22")}}
-
This Gecko-only feature, a boolean, was removed in Firefox/Gecko 22. Please use Server-Sent Events, Web Sockets, or responseText from progress events instead.
-
- -

Event handlers

- -

onreadystatechange as a property of the XMLHttpRequest instance is supported in all browsers.

- -

Since then, a number of additional event handlers have been implemented in various browsers (onload, onerror, onprogress, etc.). See Using XMLHttpRequest.

- -

More recent browsers, including Firefox, also support listening to the XMLHttpRequest events via standard {{domxref("EventTarget.addEventListener", "addEventListener()")}} APIs in addition to setting on* properties to a handler function.

- -

Methods

- -
-
{{domxref("XMLHttpRequest.abort()")}}
-
Aborts the request if it has already been sent.
-
{{domxref("XMLHttpRequest.getAllResponseHeaders()")}}
-
Returns all the response headers, separated by {{Glossary("CRLF")}}, as a string, or null if no response has been received.
-
{{domxref("XMLHttpRequest.getResponseHeader()")}}
-
Returns the string containing the text of the specified header, or null if either the response has not yet been received or the header doesn't exist in the response.
-
{{domxref("XMLHttpRequest.open()")}}
-
Initializes a request.
-
{{domxref("XMLHttpRequest.overrideMimeType()")}}
-
Overrides the MIME type returned by the server.
-
{{domxref("XMLHttpRequest.send()")}}
-
Sends the request. If the request is asynchronous (which is the default), this method returns as soon as the request is sent.
-
{{domxref("XMLHttpRequest.setRequestHeader()")}}
-
Sets the value of an HTTP request header. You must call setRequestHeader()after open(), but before send().
-
- -

Non-standard methods

- -
-
{{domxref("XMLHttpRequest.init()")}}
-
Initializes the object for use from C++ code.
-
- -
Warning: This method must not be called from JavaScript.
- -
-
{{domxref("XMLHttpRequest.openRequest()")}}
-
Initializes a request. This method is to be used from native code; to initialize a request from JavaScript code, use open() instead. See the documentation for open().
-
{{domxref("XMLHttpRequest.sendAsBinary()")}}{{deprecated_inline()}}
-
A variant of the send() method that sends binary data.
-
- -

Events

- -
-
{{domxref("XMLHttpRequest/abort_event", "abort")}}
-
Fired when a request has been aborted, for example because the program called {{domxref("XMLHttpRequest.abort()")}}.
- Also available via the {{domxref("XMLHttpRequestEventTarget/onabort", "onabort")}} property.
-
{{domxref("XMLHttpRequest/error_event", "error")}}
-
Fired when the request encountered an error.
- Also available via the {{domxref("XMLHttpRequestEventTarget/onerror", "onerror")}} property.
-
{{domxref("XMLHttpRequest/load_event", "load")}}
-
Fired when an {{domxref("XMLHttpRequest")}} transaction completes successfully.
- Also available via the {{domxref("XMLHttpRequestEventTarget/onload", "onload")}} property.
-
{{domxref("XMLHttpRequest/loadend_event", "loadend")}}
-
Fired when a request has completed, whether successfully (after {{domxref("XMLHttpRequest/load_event", "load")}}) or unsuccessfully (after {{domxref("XMLHttpRequest/abort_event", "abort")}} or {{domxref("XMLHttpRequest/error_event", "error")}}).
- Also available via the {{domxref("XMLHttpRequestEventTarget/onloadend", "onloadend")}} property.
-
{{domxref("XMLHttpRequest/loadstart_event", "loadstart")}}
-
Fired when a request has started to load data.
- Also available via the {{domxref("XMLHttpRequestEventTarget/onloadstart", "onloadstart")}} property.
-
{{domxref("XMLHttpRequest/progress_event", "progress")}}
-
Fired periodically when a request receives more data.
- Also available via the {{domxref("XMLHttpRequestEventTarget/onprogress", "onprogress")}} property.
-
{{domxref("XMLHttpRequest/timeout_event", "timeout")}}
-
Fired when progress is terminated due to preset time expiring.
- Also available via the {{domxref("XMLHttpRequestEventTarget/ontimeout", "ontimeout")}} property.
-
- -

Specifications

- - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('XMLHttpRequest')}}{{Spec2('XMLHttpRequest')}}Live standard, latest version
- -

Browser compatibility

- - - -
{{Compat("api.XMLHttpRequest")}}
- -

See also

- - diff --git a/files/id/web/api/xmlhttprequest/using_xmlhttprequest/index.html b/files/id/web/api/xmlhttprequest/using_xmlhttprequest/index.html deleted file mode 100644 index 1de088b719..0000000000 --- a/files/id/web/api/xmlhttprequest/using_xmlhttprequest/index.html +++ /dev/null @@ -1,793 +0,0 @@ ---- -title: Using XMLHttpRequest -slug: Web/API/XMLHttpRequest/Using_XMLHttpRequest -translation_of: Web/API/XMLHttpRequest/Using_XMLHttpRequest ---- -
{{APIRef("XMLHttpRequest")}}
- -
Dalam panduan ini, kita akan melihat bagaimana cara untuk mengunakan {{domxref("XMLHttpRequest")}}  untuk menyelesaikan permasalahan HTTP request yang dalam penggunaan untuk pertukaran data antara halaman web dan server. Contoh umum dan kasus penggunaan lebih jelas untuk XMLHttpRequest disertakan.
- -
- -
Untuk mengirim HTTP request,  buatlah sebuah object XMLHttpRequest , buka sebuah URL dan kirim request tersebut. setelah transaksi selesai, objek akan berisi informasi yang berguna seperti badan respon dan status HTTP dari hasilnya.
- -
- -
function reqListener () {
-  console.log(this.responseText);
-}
-
-var oReq = new XMLHttpRequest();
-oReq.addEventListener("load", reqListener);
-oReq.open("GET", "http://www.example.org/example.txt");
-oReq.send();
- -

Tipe-Tipe dari Request

- -

Sebuh request yang dihasilkan melalui XMLHttpRequest dapat mengambil data dari salah satu cara, asynchronously or synchronously. Tipe dari request ditentukan onleh opsi async argument (argument ke-tiga) yang telah diset dialam metode {{domxref("XMLHttpRequest.open()")}}. Jika argument tersebut true atau tidak ditentukan. XMLHttpRequest akan diproses secara asynchronous,jika tidak proses akan berjalan secara synchronous. Diskusi detail dan demonstrasi dari kedua cara merequest tersebut dapat ditemukan pada halaman synchronous and asynchronous requests. Jangan gunakan permintaan synchronous di luar Pekerja Web.

- -
Note: Dimulai dari Gecko 30.0 {{ geckoRelease("30.0") }}, permintaan synchronous pada utas utama telah ditinggalkan karena efek negatif terhadap pengalaman pengguna.
- -
Note: fungsi konstruksi XMLHttpRequest tidak terbatas hanya pada dokumen XML. Itu dimulai dengan "XML" karena ketika itu dibuat format utama yang awalnya digunakan untuk Asynchronous Data Exchange adalah XML
- -

Menangani Respons

- -

Ada beberapa jenis atribut respons  ditentukan oleh spesifikasi standar untuk {domxref("XMLHttpRequest.XMLHttpRequest", "XMLHttpRequest()")}} constructor. Ini memberi tahu klien membuat informasi penting XMLHttpRequest tentang status respons. Beberapa kasus di mana berurusan dengan jenis respons non-teks mungkin melibatkan beberapa manipulasi dan analisis diuraikan dalam bagian berikut.

- -

Menganalisa dan Memanipulasi Properti responseXML

- -

Jika kamu mengunakan XMLHttpRequest  untuk mendapatkan konten dokumen XML jarak jauh, properti {{domxref("XMLHttpRequest.responseXML", "responseXML")}}  akan menjadi objek DOM yang berisi dokumen XML parsing. Ini terbentuk sulit untuk dimanipulasi dan dianalisis. Ada empat cara utama untuk menganalisis dokumen XML ini:

- -
    -
  1. Menggunakan XPath untuk mengatasi (atau menunjuk ke) bagian-bagiannya.
  2. -
  3. Secara manual Parsing dan men-serialisasikan XML ke string atau objek
  4. -
  5. Menggunakan {{domxref("XMLSerializer")}} untuk meng-serialisasi Pohon DOM ke strings atau ke file.
  6. -
  7. {{jsxref("RegExp")}} bisa digunakan jika kamu selalu tau konten dari XML document sebelumnya. Kamu mungkin ingin menghapus jeda baris, jika Anda menggunakan RegEx untuk memindai berkenaan dengan jeda baris. Namun, metode ini adalah "pilihan terakhir" karena jika kode XML sedikit berubah, metode ini kemungkinan akan gagal.
  8. -
- -
-

Note: XMLHttpRequest sekarang dapat menafsirkan HTML untuk Anda menggunakan properti {{domxref("XMLHttpRequest.responseXML", "responseXML")}}. Baca artikel HTML dalam XMLHttpRequest untuk mempelajari cara untuk melakukannya.

-
- -

Memproses sebuah Properti responseText yang Berisi HTML Dokument

- -

Jika kamu mengunakan XMLHttpRequest untuk mendapatkan konten dari halaman web HTML jarak jauh. Properti {{domxref("XMLHttpRequest.responseText", "responseText")}} adalah sebuah string yang berisi data HTML mentah. Hal ini terbukti sulit untuk dimanipulasi dan dianalisi. Karenanya ada tiga cara utama untuk

- -

If you use XMLHttpRequest to get the content of a remote HTML webpage, the {{domxref("XMLHttpRequest.responseText", "responseText")}} property is a string containing the raw HTML. This could prove difficult to manipulate and analyze. Ada tiga cara utama untuk menganalisis dan mengurai string HTML mentah ini:

- -
    -
  1. Use the XMLHttpRequest.responseXML property as covered in the article HTML in XMLHttpRequest.
  2. -
  3. Inject the content into the body of a document fragment via fragment.body.innerHTML and traverse the DOM of the fragment.
  4. -
  5. {{jsxref("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.
  6. -
- -

Handling binary data

- -

Although {{domxref("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 {{domxref("XMLHttpRequest.overrideMimeType", "overrideMimeType()")}} method on the XMLHttpRequest object and is a workable solution.

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

However, more modern techniques are available, since the {{domxref("XMLHttpRequest.responseType", "responseType")}} attribute now supports a number of additional content types, which makes sending and receiving binary data much easier.

- -

For example, consider this snippet, which uses the responseType of "arraybuffer" to fetch the remote content into a {{jsxref("ArrayBuffer")}} object, which stores the raw binary data.

- -
var oReq = new XMLHttpRequest();
-
-oReq.onload = function(e) {
-  var arraybuffer = oReq.response; // not responseText
-  /* ... */
-}
-oReq.open("GET", url);
-oReq.responseType = "arraybuffer";
-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 {{event("progress")}} event monitoring of XMLHttpRequest transfers follows the specification for progress events: these events implement the {{domxref("ProgressEvent")}} interface. The actual events you can monitor to determine the state of an ongoing transfer are:

- -
-
{{event("progress")}}
-
The amount of data that has been retrieved has changed.
-
{{event("load")}}
-
The transfer is complete; all data is now in the response
-
- -
var oReq = new XMLHttpRequest();
-
-oReq.addEventListener("progress", updateProgress);
-oReq.addEventListener("load", transferComplete);
-oReq.addEventListener("error", transferFailed);
-oReq.addEventListener("abort", transferCanceled);
-
-oReq.open();
-
-// ...
-
-// progress on transfers from the server to the client (downloads)
-function updateProgress (oEvent) {
-  if (oEvent.lengthComputable) {
-    var percentComplete = oEvent.loaded / oEvent.total * 100;
-    // ...
-  } else {
-    // Unable to compute progress information since the total size is unknown
-  }
-}
-
-function transferComplete(evt) {
-  console.log("The transfer is complete.");
-}
-
-function transferFailed(evt) {
-  console.log("An error occurred while transferring the file.");
-}
-
-function transferCanceled(evt) {
-  console.log("The transfer has been canceled by the user.");
-}
- -

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);
-oReq.upload.addEventListener("load", transferComplete);
-oReq.upload.addEventListener("error", transferFailed);
-oReq.upload.addEventListener("abort", transferCanceled);
-
-oReq.open();
-
- -
Note: Progress events are not available for the file: protocol.
- -
-

Note: Starting in {{Gecko("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.

-
- -
-

Note: As of {{Gecko("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);
-
-function loadEnd(e) {
-  console.log("The transfer finished (although we don't know if it succeeded or not).");
-}
-
- -

Note there is no way to be certain, from the information received by 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 the FormData API is the simplest and fastest, but has the disadvantage that data collected can not be stringified.
- Using only AJAX is more complex, but typically more flexible and powerful.

- -

Using nothing but XMLHttpRequest

- -

Submitting forms without the FormData API does not require other APIs for most use cases. The only case where you need an additional API is if you want to upload one or more files, where you use the {{domxref("FileReader")}} API.

- -

A brief introduction to the submit methods

- -

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

- - - -

Now, consider the submission of 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 examples, depending on the encoding type you are using:

- - - -

However, 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 effects are done automatically by the web browser whenever you submit a {{HTMLElement("form")}}. If you want to perform the same effects using JavaScript you have to instruct the interpreter about everything. Therefore, how to send forms in pure AJAX is too complex to be explained here in detail. For this reason, here we place a complete (yet didactic) framework, able to use all four ways to submit, and 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() Polyfill ::
-|*|
-|*|  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.
-|*|  https://www.gnu.org/licenses/gpl-3.0-standalone.html
-|*|
-|*|  Syntax:
-|*|
-|*|   AJAXSubmit(HTMLFormElement);
-\*/
-
-var AJAXSubmit = (function () {
-
-  function ajaxSuccess () {
-    /* console.log("AJAXSubmit - Success!"); */
-    console.log(this.responseText);
-    /* you can get the serialized data through the "submittedData" custom property: */
-    /* console.log(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) {
-        /* NOTE: this will submit _all_ submit buttons. Detecting the correct one is non-trivial. */
-        /* 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 this, create a page named register.php (which is the action attribute of these sample forms), and put the following minimalistic content:

- -
<?php
-/* register.php */
-
-header("Content-type: text/plain");
-
-/*
-NOTE: You should never use `print_r()` in production scripts, or
-otherwise output client-submitted data without sanitizing it first.
-Failing to sanitize can lead to cross-site scripting vulnerabilities.
-*/
-
-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 to activate this script is simply:

- -
AJAXSubmit(myForm);
- -
Note: This framework uses the {{domxref("FileReader")}} API to transmit file uploads. This is a recent API and is not implemented in IE9 or below. For this reason, the AJAX-only upload is considered an experimental technique. If you do not need to upload binary files, this framework works fine in most browsers.
- -
Note: The best way to send binary content is via {{jsxref("ArrayBuffer", "ArrayBuffers")}} or {{domxref("Blob", "Blobs")}} in conjuncton with the {{domxref("XMLHttpRequest.send()", "send()")}} method and possibly the {{domxref("FileReader.readAsArrayBuffer()", "readAsArrayBuffer()")}} method of the FileReader API. But, since the aim of this script is to work with a stringifiable raw data, we used the {{domxref("XMLHttpRequest.sendAsBinary()", "sendAsBinary()")}} method in conjunction with the {{domxref("FileReader.readAsBinaryString()", "readAsBinaryString()")}} method of the FileReader API. As such, the above script makes sense only when you are dealing with small files. If you do not intend to upload binary content, consider instead using the FormData API.
- -
Note: The non-standard sendAsBinary method is considered deprecated as of Gecko 31 {{geckoRelease(31)}} and will be removed soon. The standard send(Blob data) method can be used instead.
- -

Using FormData objects

- -

The {{domxref("XMLHttpRequest.FormData", "FormData")}} constructor lets you compile a set of key/value pairs to send using XMLHttpRequest. Its primary use is in sending form data, but can also be used independently from a form in order to transmit user keyed data. The transmitted data is in the same format the form's submit() method uses to send 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 purposes here is a translation of the previous example transformed to use the FormData API. Note the brevity of the code:

- -
-
<!doctype html>
-<html>
-<head>
-<meta http-equiv="Content-Type" charset="UTF-8" />
-<title>Sending forms with FormData &ndash; MDN</title>
-<script>
-"use strict";
-
-function ajaxSuccess () {
-  console.log(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);
-    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, {{domxref("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 {{domxref("FileReader")}} API also: files are automatically loaded and uploaded.
- -

Get last modified date

- -
function getHeaderTime () {
-  console.log(this.getResponseHeader("Last-Modified"));  /* A valid GMTString date or null */
-}
-
-var oReq = new XMLHttpRequest();
-oReq.open("HEAD" /* use HEAD if you only need the headers! */, "yourpage.html");
-oReq.onload = getHeaderTime;
-oReq.send();
- -

Do something when last modified date changes

- -

Let's create two functions:

- -
function getHeaderTime () {
-  var nLastVisit = parseFloat(window.localStorage.getItem('lm_' + this.filepath));
-  var nLastModif = Date.parse(this.getResponseHeader("Last-Modified"));
-
-  if (isNaN(nLastVisit) || nLastModif > nLastVisit) {
-    window.localStorage.setItem('lm_' + this.filepath, Date.now());
-    isFinite(nLastVisit) && this.callback(nLastModif, nLastVisit);
-  }
-}
-
-function ifHasChanged(sURL, fCallback) {
-  var oReq = new XMLHttpRequest();
-  oReq.open("HEAD" /* use HEAD - we only need the headers! */, sURL);
-  oReq.callback = fCallback;
-  oReq.filepath = sURL;
-  oReq.onload = getHeaderTime;
-  oReq.send();
-}
- -

And to test:

- -
/* Let's test the file "yourpage.html"... */
-
-ifHasChanged("yourpage.html", function (nModif, nVisit) {
-  console.log("The page '" + this.filepath + "' has been changed on " + (new Date(nModif)).toLocaleString() + "!");
-});
- -

If you want to know if the current page has changed, please read the article about {{domxref("document.lastModified")}}.

- -

Cross-site XMLHttpRequest

- -

Modern browsers support cross-site requests by implementing the Cross-Origin Resource Sharing (CORS) standard. As long as the server is configured to allow requests from your web application's origin, XMLHttpRequest will work. Otherwise, an INVALID_ACCESS_ERR exception is thrown.

- -

Bypassing the cache

- -

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

- -
http://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
-
- -

As the local cache is indexed by URL, this causes every request to be unique, thereby bypassing the cache.

- -

You can automatically adjust URLs using the following code:

- -
var oReq = new XMLHttpRequest();
-
-oReq.open("GET", url + ((/\?/).test(url) ? "&" : "?") + (new Date()).getTime());
-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 conclude with an XMLHttpRequest receiving status=0 and statusText=null, this means 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 subsequently open(). This case can happen, for example, when one has an XMLHttpRequest that gets fired on an onunload event for a window, the expected XMLHttpRequest is created when the window to be closed is still there, and finally sending the request (in otherwords, open()) when this window has lost its focus and another window gains focus. The most effective way to avoid this problem is to set a listener on the new window's {{event("activate")}} event which is set once the terminated window has its {{event("unload")}} event triggered.

- -

Workers

- -

Setting overrideMimeType does not work from a {{domxref("Worker")}}.  See {{bug(678057)}} for more details.  Other browsers may handle this differently.

- -

Specifications

- - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('XMLHttpRequest')}}{{Spec2('XMLHttpRequest')}}Live standard, latest version
- -

Browser compatibility

- - - -

{{Compat("api.XMLHttpRequest")}}

- -

See also

- -
    -
  1. MDN AJAX introduction
  2. -
  3. HTML in XMLHttpRequest
  4. -
  5. HTTP access control
  6. -
  7. How to check the security state of an XMLHTTPRequest over SSL
  8. -
  9. XMLHttpRequest - REST and the Rich User Experience
  10. -
  11. Microsoft documentation
  12. -
  13. "Using the XMLHttpRequest Object" (jibbering.com)
  14. -
  15. The XMLHttpRequest object: WHATWG specification
  16. -
-- cgit v1.2.3-54-g00ecf