From de5c456ebded0e038adbf23db34cc290c8829180 Mon Sep 17 00:00:00 2001 From: Florian Merz Date: Thu, 11 Feb 2021 14:49:24 +0100 Subject: unslug pl: move --- files/pl/web/api/xmlhttprequest/index.html | 233 ++++++++ .../xmlhttprequest/using_xmlhttprequest/index.html | 657 +++++++++++++++++++++ 2 files changed, 890 insertions(+) create mode 100644 files/pl/web/api/xmlhttprequest/index.html create mode 100644 files/pl/web/api/xmlhttprequest/using_xmlhttprequest/index.html (limited to 'files/pl/web/api/xmlhttprequest') diff --git a/files/pl/web/api/xmlhttprequest/index.html b/files/pl/web/api/xmlhttprequest/index.html new file mode 100644 index 0000000000..70711f894b --- /dev/null +++ b/files/pl/web/api/xmlhttprequest/index.html @@ -0,0 +1,233 @@ +--- +title: XMLHttpRequest +slug: XMLHttpRequest +tags: + - AJAX + - Wszystkie_kategorie + - XMLHttpRequest +translation_of: Web/API/XMLHttpRequest +--- +

+

Obiekt XMLHttpRequest jest obiektem JavaScript zaprojektowanym przez firmę Microsoft i zaadaptowanym w programach Mozilla. Służy do pobierania danych przy użyciu protokołu HTTP. Wbrew nazwie może być stosowany do obsługi dokumentów w wielu formatach, nie tylko XML, ale także JSON.

Artykuł ten zawiera między innymi informacje specyficzne dla silnika Gecko lub kodu uprzywilejowanego, takiego jak kod rozszerzeń programu Firefox. +

W silniku Gecko w obiekcie zaimplementowano interfejsy nsIJSXMLHttpRequest i nsIXMLHttpRequest. W najnowszych wersjach Gecko dokonano pewnych modyfikacji tego obiektu — patrz artykuł Zmiany w obiekcie XMLHttpRequest w Gecko 1.8. +

+

Podstawy

+

Korzystanie z obiektu XMLHttpRequest jest bardzo proste. Należy utworzyć instancję obiektu, otworzyć adres URL, po czym wysłać żądanie. Zwrócony przez serwer kod stanu HTTP, jak również pobrany dokument są następnie dostępne jako własności obiektu żądania. +

{{ Note("W wersjach Firefoksa starszych niż 3 żądania są zawsze wysyłane przy użyciu kodowania UTF-8. W programie Firefox 3 dokument jest wysyłany poprawnie przy użyciu kodowania określonego we własności data.inputEncoding (gdzie data to obiekt przekazany do metody send(); obiekt ten nie może być wartością null). Jeżeli nie określono żadnego kodowania, używane jest kodowanie UTF-8.") }} +

+

Przykład

+
var req = new XMLHttpRequest();
+req.open('GET', 'http://www.mozilla.org/', false);
+req.send(null);
+if(req.status == 200)
+  dump(req.responseText);
+
+
Uwaga: W tym przykładzie dane pobierane są w sposób synchroniczny — wykonanie powyższego kodu JavaScript spowoduje zablokowanie interfejsu użytkownika do momentu zakończenia pobierania. Nie należy wykorzystywać podanego kodu w praktyce.
+
Uwaga: W żądaniach synchronicznych nie należy korzystać z funkcji onreadystatechange — w przeciwnym przypadku w wersjach Firefoksa starszych niż wersja 3 zostanie ona wywołana. Program Firefox 3 jest zablokowany do momentu ukończenia procesu obsługi żądania (tak jak w powyższym przykładzie). Program Firefox 2 działa w ten sam sposób, jeżeli tylko funkcja onreadystatechange nie zostanie zaimplementowana.
+

Przykład dla protokołu innego niż HTTP

+
var req = new XMLHttpRequest();
+req.open('GET', 'file:///home/user/file.json', false);
+req.send(null);
+if(req.status == 0)
+  dump(req.responseText);
+
+
Uwaga: protokoły file:/// i ftp:// nie zwracają kodu stanu HTTP, stąd w ich przypadku własność status zwraca wartość zero, a własność statusText zawiera pusty ciąg znaków. Aby uzyskać więcej informacji, patrz {{ Bug(331610) }}.
+

Zastosowanie asynchroniczne

+

W przypadku korzystania z obiektów XMLHttpRequest w rozszerzeniu Firefoksa pobierane dane powinny być ładowane asynchronicznie. Po całkowitym pobraniu danych przekazywane jest wywołanie zwrotne (ang. callback), co pozwala na normalną pracę przeglądarki podczas przetwarzania żądania. +

+

Przykład

+
var req = new XMLHttpRequest();
+req.open('GET', 'http://www.mozilla.org/', true); /* Argument trzeci, wartość true, określa, że żądanie ma być asynchroniczne */
+req.onreadystatechange = function (aEvt) {
+  if (req.readyState == 4) {
+     if(req.status == 200)
+      dump(req.responseText);
+     else
+      dump("Błąd podczas ładowania strony\n");
+  }
+};
+req.send(null);
+
+

Monitorowanie postępu

+

Obiekt XMLHttpRequest umożliwia monitorowanie wielu zdarzeń, które mogą wystąpić podczas przetwarzania żądania — służą do tego okresowe powiadomienia o postępie przetwarzania, komunikaty o błędach itp. +

Jeżeli na przykład w czasie pobierania dokumentu do użytkownika mają być wysyłane informacje o postępie przetwarzania, można skorzystać z poniższego kodu: +

+
function onProgress(e) {
+  var percentComplete = (e.position / e.totalSize)*100;
+  ...
+}
+
+function onError(e) {
+  alert("Podczas pobierania dokumentu wystąpił błąd " + e.target.status + ".");
+}
+
+function onLoad(e) {
+  // ...
+}
+// ...
+var req = new XMLHttpRequest();
+req.onprogress = onProgress;
+req.open("GET", url, true);
+req.onload = onLoad;
+req.onerror = onError;
+req.send(null);
+
+

Atrybuty zdarzenia onprogress, position i totalSize, wskazują odpowiednio liczbę pobranych dotychczas bajtów i całkowitą liczbę bajtów, które mają zostać pobrane. +

Dla wszystkich zdarzeń atrybut target wskazuje powiązany obiekt XMLHttpRequest. +

+
Uwaga: przy korzystaniu z funkcji obsługi zdarzeń w dokumentach XML reprezentowanych przez obiekt XMLDocument program Firefox 3 sprawdza, czy wartości własności target, currentTarget i this obiektu zdarzenia wskazują na właściwe obiekty. Aby uzyskać szczegółowe informacje, patrz {{ Bug(198595) }}.
+

Inne własności i metody

+

Oprócz własności i metod omówionych powyżej obiekty XMLHttpRequest obsługują również inne przydatne własności i metody. +

+

responseXML

+

Jeżeli ładowany jest dokument XML, własność responseXML zawiera treść pobranego dokumentu w postaci obiektu XmlDocument, do którego można uzyskać za pomocą metod DOM. Jeżeli serwer wysyła poprawnie sformatowany dokument XML, ale nie jest okreśony nagłówek XML Content-Type, za pomocą metody overrideMimeType() można wymusić przetwarzanie dokumentu jako kodu XML. Jeżeli dokument XML wysyłany z serwera nie jest sformatowany poprawnie, własność responseXML zwraca wartość null, niezależnie od wymuszonego typu danych. +

+

overrideMimeType()

+

Za pomocą tej metody można wymusić sposób obsługi dokumentu, wskazując określony typ danych. Metoda ta przydaje się w sytuacji, gdy do przetwarzania otrzymanych danych ma być użyta własność responseXML, serwer wysyła dane w formacie XML, ale nie jest wysyłany poprawny nagłówek Content-Type.

+
Uwaga: metodę tę należy wywołać przed użyciem metody send().
+
var req = new XMLHttpRequest();
+req.open('GET', 'http://www.mozilla.org/', true);
+req.overrideMimeType('text/xml');
+req.send(null);
+
+

setRequestHeader()

+

Za pomocą tej metody można ustawić dowolny nagłówek HTTP żądania przed wysłaniem go. +

+
Uwaga: Przed wywołaniem tej metody należy użyć metody open().
+
var req = new XMLHttpRequest();
+req.open('GET', 'http://www.mozilla.org/', true);
+req.setRequestHeader("X-Foo", "Bar");
+req.send(null);
+
+

getResponseHeader()

+

Za pomocą tej metody można pobrać nagłówek HTTP ustawiony w odpowiedzi przesłanej przez serwer. +

+
var req = new XMLHttpRequest();
+req.open('GET', 'http://www.mozilla.org/', false);
+req.send(null);
+dump("Content-Type: " + req.getResponseHeader("Content-Type") + "\n");
+
+

abort()

+

Metoda ta służy do anulowania żądania, które jest właśnie wykonywane. +

+
var req = new XMLHttpRequest();
+req.open('GET', 'http://www.mozilla.org/', false);
+req.send(null);
+req.abort();
+
+

mozBackgroundRequest

+

{{ Fx_minversion_inline(3) }} Za pomocą tej własności można wyłączyć okna dialogowe uwierzytelniania i niewłaściwego certyfikatu, które mogą pojawiać się przy wysyłaniu żądania. Żądanie, dla którego ustawiono tę własność, nie będzie ponadto anulowane nawet w przypadku zamknięcia okna, z którego zostało wysłane. Własność ta działa wyłącznie w kodzie chrome. +

+
var req = new XMLHttpRequest();
+req.mozBackgroundRequest = true;
+req.open('GET', 'http://www.mozilla.org/', true);
+req.send(null);
+
+

Zastosowanie w komponentach XPCOM

+
Uwaga: W przypadku korzystania z obiektów XMLHttpRequest w komponentach JavaScript XPCOM wymagane są pewne zmiany.
+

W komponentach JavaScript XPCOM niemożliwe jest utworzenie obiektów XMLHttpRequest za pomocą konstruktora XMLHttpRequest() — nie jest on zdefiniowany wewnątrz komponentów i jego wywołanie powoduje wystąpienie błędu. W celu utworzenia i użycia obiektu należy skorzystać z innej składni. +

Zamiast kodu: +

+
var req = new XMLHttpRequest();
+req.onprogress = onProgress;
+req.onload = onLoad;
+req.onerror = onError;
+req.open("GET", url, true);
+req.send(null);
+
+

należy użyć: +

+
var req = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"]
+                    .createInstance(Components.interfaces.nsIXMLHttpRequest);
+req.onprogress = onProgress;
+req.onload = onLoad;
+req.onerror = onError;
+req.open("GET", url, true);
+req.send(null);
+
+

W kodzie w języku C++ można za pomocą metody QueryInterface przesłać komponent do interfejsu nsIEventTarget, aby ustawić procedury obsługi zdarzeń; bezpośrednie korzystanie z kanału jest jednak lepszą techniką. +

+

Ograniczona liczba jednoczesnych połączeń nawiązywanych przez obiekty XMLHttpRequest

+

Maksymalna liczba połączeń, określona w preferencji network.http.max-persistent-connections-per-server (dostępnej w oknie about:config), jest domyślnie ograniczona do 2. Niektóre interaktywne strony internetowe, na których używane są obiekty XMLHttpRequest, mogą podtrzymywać otwarte połączenie. Otwarcie dwóch lub trzech takich stron w osobnych kartach lub oknach może spowodować awarię przeglądarki, w wyniku której zawartość okien nie będzie odświeżana, a sama aplikacja przestanie odpowiadać. +

+

Zawartość binarna

+

Chociaż wysyłanie i odbieranie danych tekstowych jest najbardziej popularnym zastosowaniem obiektu XMLHttpRequest, za jego pomocą można także przesyłać zawartość binarną. +

+

Pobieranie zawartości binarnej

+
// Synchroniczne pobieranie PLIKÓW BINARNYCH za pomocą obiektu XMLHttpRequest
+function load_binary_resource(url) {
+  var req = new XMLHttpRequest();
+  req.open('GET', url, false);
+  //XHR binary charset opt by Marcus Granado 2006 [http://mgran.blogspot.com]
+  req.overrideMimeType('text/plain; charset=x-user-defined');
+  req.send(null);
+  if (req.status != 200) return '';
+  return req.responseText;
+}
+
+var filestream = load_binary_resource(url);
+// x to offset (tzn. pozycja) bajtu w zwróconym strumieniu pliku binarnego.
+// Wartość x powinna mieścić się w zakresie od 0 do filestream.length-1.
+var abyte = filestream.charCodeAt(x) & 0xff; // usunięcie najbardziej znaczącego (górnego) bajtu (f7)
+
+

Szczegółowe wyjaśnienia można znaleźć w artykule dotyczącym pobierania zawartości binarnej za pomocą obiektu XMLHttpRequest. Patrz także Pobieranie plików. +

+

Wysyłanie zawartości binarnej

+

W poniższym przykładzie zawartość binarna jest wysyłana asynchronicznie za pomocą metody POST. Zmienna aBody reprezentuje wysyłane dane.

+
 var req = new XMLHttpRequest();
+ req.open("POST", url, true);
+ // ustawienie odpowiednich nagłówków i typu MIME
+ req.setRequestHeader("Content-Length", 741);
+ req.sendAsBinary(aBody);
+
+

Zawartość binarną można także wysłać, przekazując instancję interfejsu nsIFileInputStream do metody req.send(). W takim przypadku nie jest konieczne ustawienie nagłówka Content-Length:

+
// Tworzenie strumienia z pliku.
+var stream = Components.classes["@mozilla.org/network/file-input-stream;1"]
+                       .createInstance(Components.interfaces.nsIFileInputStream);
+stream.init(file, 0x04 | 0x08, 0644, 0x04); // file to instancja interfejsu nsIFile
+
+// Próba określenia typu MIME pliku
+var mimeType = "text/plain";
+try {
+  var mimeService = Components.classes["@mozilla.org/mime;1"].getService(Components.interfaces.nsIMIMEService);
+  mimeType = mimeService.getTypeFromFile(file); // file to instancja interfejsu nsIFile
+}
+catch(e) { /* W tym przypadku zastosuj po prostu typ text/plain */ }
+
+// Wysłanie
+var req = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"]
+                    .createInstance(Components.interfaces.nsIXMLHttpRequest);
+req.open('PUT', url, false); /* synchronicznie! */
+req.setRequestHeader('Content-Type', mimeType);
+req.send(stream);
+

Pomijanie pamięci podręcznej

+

Obiekt XMLHttpRequest próbuje z reguły pobrać zawartość z lokalnej pamięci podręcznej. Aby pominąć tę próbę, należy skorzystać z poniższego kodu: +

+
 var req = new XMLHttpRequest();
+ req.channel.loadFlags |= Components.interfaces.nsIRequest.LOAD_BYPASS_CACHE;
+ req.open('GET', url, false);
+ req.send(null);
+
+

Istnieje także alternatywny sposób pomijania pamięci podręcznej, opisany tutaj: +

+
 var req = new XMLHttpRequest();
+ req.open("GET", url += (url.match(/\?/) == null ? "?" : "&") + (new Date()).getTime(), false);
+ req.send(null);
+
+

Do adresu URL dodawany jest parametr zawierający znacznik czasu (odpowiednio wstawiane są znaki ? i &). Na przykład adres http://foo.com/bar.html jest przekształcany na http://foo.com/bar.html?12345, a http://foo.com/bar.html?foobar=baz zostaje zamieniany na http://foo.com/bar.html?foobar=baz&12345. Lokalna pamięć podręczna jest indeksowana przy użyciu adresów URL; tymczasem, ponieważ każdy adres URL w obiekcie XMLHttpRequest jest niepowtarzalny, pamięć podręczna jest zawsze pomijana. +

+

Pobieranie kodu JSON i JavaScript w rozszerzeniach

+

W rozszerzeniach do przetwarzania pobieranego z sieci kodu JSON lub JavaScript nie należy używać metody eval(). Szczegółowe informacje można znaleźć w artykule Pobieranie kodu JSON i JavaScript w rozszerzeniach. +

+

Odnośniki

+
  1. AJAX: wprowadzenie +
  2. Obiekt XMLHttpRequest - architektura REST i zaawansowane interfejsy użytkownika (artykuł w j. ang.) +
  3. Dokumentacja XULPlanet (artykuł w j. ang.) +
  4. Dokumentacja firmy Microsoft (artykuł w j. ang.) +
  5. Materiały dla programistów Apple (artykuł w j. ang.) +
  6. Korzystanie z obiektu XMLHttpRequest (jibbering.com) (artykuł w j. ang.) +
  7. Obiekt XMLHttpRequest: robocza wersja specyfikacji W3C (artykuł w j. ang.) +
+
+
+{{ languages( { "en": "en/XMLHttpRequest", "es": "es/XMLHttpRequest", "fr": "fr/XMLHttpRequest", "it": "it/XMLHttpRequest", "ja": "ja/XMLHttpRequest", "ko": "ko/XMLHttpRequest", "zh-cn": "cn/XMLHttpRequest" } ) }} diff --git a/files/pl/web/api/xmlhttprequest/using_xmlhttprequest/index.html b/files/pl/web/api/xmlhttprequest/using_xmlhttprequest/index.html new file mode 100644 index 0000000000..b804b9992c --- /dev/null +++ b/files/pl/web/api/xmlhttprequest/using_xmlhttprequest/index.html @@ -0,0 +1,657 @@ +--- +title: Wykorzystanie XMLHttpRequest +slug: XMLHttpRequest/Using_XMLHttpRequest +translation_of: Web/API/XMLHttpRequest/Using_XMLHttpRequest +--- +

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.

+
+ Note: Starting with Gecko 30.0 {{ geckoRelease("30.0") }}, synchronous requests on the main thread have been deprecated due to the negative effects to the user experience.
+

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. +
  3. Using JXON to convert it into a JavaScript Object tree.
  4. +
  5. Manually Parsing and serializing XML to strings or objects.
  6. +
  7. Using XMLSerializer to serialize DOM trees to strings or to files.
  8. +
  9. 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.
  10. +
+

Analyzing and manipulating a responseText property containing an HTML document

+
+ Note: The W3C XMLHttpRequest specification allows HTML parsing via the 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. Use the XMLHttpRequest.responseXML property.
  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. 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 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.onload = function(e) {
+  var arraybuffer = oReq.response; // not responseText
+  /* ... */
+}
+oReq.open("GET", url, true);
+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 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.
+
+ Note: Currently there are open bugs for the progress event that are still affecting version 25 of Firefox on OS X and Linux.
+
+

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

+ +

The second way (using the FormData API) is the simplest and the fastest, but has the disadvantage that the data collected can not be stringified.
+ The first way is instead the most complex but also lends itself to be the most flexible and powerful.

+

Using nothing but XMLHttpRequest

+

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:

+ +

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:

+ +

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() 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.
+|*|  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, 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");
+
+/*
+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 of this script is the following:

+
AJAXSubmit(myForm);
+
+ Note: This framework uses the 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 work fine in most browsers.
+
+ Note: The best way to send binary content is via ArrayBuffers or Blobs in conjuncton with the send() method and possibly the readAsArrayBuffer() method of the FileReader API. But, since the aim of this script is to work with a stringifiable raw data, we used the sendAsBinary() method in conjunction with the 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 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, {{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 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 = new 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(window.localStorage.getItem('lm_' + this.filepath)),
+    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, true);
+  oReq.callback = fCallback;
+  oReq.filepath = sURL;
+  oReq.onload = getHeaderTime;
+  oReq.send();
+}
+

Test:

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

If you want to know whether the current page has changed, please read the article about document.lastModified.

+

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", "nsIXMLHttpRequest");
+
+

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

See also

+
    +
  1. MDN AJAX introduction
  2. +
  3. HTTP access control
  4. +
  5. How to check the security state of an XMLHTTPRequest over SSL
  6. +
  7. XMLHttpRequest - REST and the Rich User Experience
  8. +
  9. Microsoft documentation
  10. +
  11. Apple developers' reference
  12. +
  13. "Using the XMLHttpRequest Object" (jibbering.com)
  14. +
  15. The XMLHttpRequest Object: W3C Specification
  16. +
  17. Web Progress Events specification
  18. +
-- cgit v1.2.3-54-g00ecf