Synchronous and asynchronous requests

  • Revision slug: DOM/XMLHttpRequest/Synchronous_and_Asynchronous_Requests
  • Revision title: Synchronous and asynchronous requests
  • Revision id: 341813
  • Created:
  • Creator: fusionchess
  • Is current revision? No
  • Comment

Revision Content

XMLHttpRequest supports both synchronous and asynchronous communications.

Note: You shouldn't use synchronous XMLHttpRequests because, due to the inherently asynchronous nature of networking, there are various ways memory and events can leak when using synchronous requests. The only exception is that synchronous requests work well inside Workers.

In versions of Firefox prior to Firefox 3, synchronous XMLHttpRequest requests blocked the user interface.  In order to make it possible for the user to terminate frozen requests, Firefox 3 no longer does so.

Asynchronous request

If you use XMLHttpRequest from an extension, you should use it asynchronously.  In this case, you receive a callback when the data has been received, which lets the browser continue to work as normal while your request is being handled.

Example: send a file to the console log

This is the simplest usage of asynchronous XMLHttpRequest.

var oReq = new XMLHttpRequest();
oReq.open("GET", "http://www.mozilla.org/", true);
oReq.onreadystatechange = function (oEvent) {
  if (oReq.readyState === 4) {
    if (oReq.status === 200) {
      console.log(oReq.responseText);
    } else {
      console.log("Error", oReq.statusText);
    }
  }
};
oReq.send(null); 

Line 2 specifies true for its third parameter to indicate that the request should be handled asynchronously.

Line 3 creates an event handler function object and assigns it to the request's onreadystatechange attribute.  This handler looks at the request's readyState to see if the transaction is complete in line 4, and if it is, and the HTTP status is 200, dumps the received content.  If an error occurred, an error message is displayed.

Line 12 actually initiates the request.  The callback routine is called whenever the state of the request changes.

Example: creating a standard function to read external files

In some cases you must read many external files. This is a standard function which uses the XMLHttpRequest object asynchronously in order to switch the content of the read file to a specified listener.

function loadFile (sURL, fCallback /*, argumentToPass1, argumentToPass2, etc. */) {
  var aPassArgs = Array.prototype.slice.call(arguments, 2), oReq = new XMLHttpRequest();
  oReq.onreadystatechange = function() {
    if (oReq.readyState === 4) { 
      if (oReq.status === 200) {
        fCallback.apply(oReq, aPassArgs);
      } else {
        console.log("Error", oReq.statusText);
      }
    }
  };
  oReq.open("GET", sURL, true);
  oReq.send(null);
}

Usage:

function showMessage (sMsg) {
  alert(sMsg + this.responseText);
}

loadFile("message.txt", showMessage, "New message!\n");

Line 1 declares a function which will pass all arguments after the third to the fCallback function when the file has been loaded.

Line 3 creates an event handler function object and assigns it to the request's onreadystatechange attribute.  This handler looks at the request's readyState to see if the transaction is complete in line 4, and if it is, and the HTTP status is 200, calls the callback function.  If an error occurred, an error message is displayed.

Line 12 specifies true for its third parameter to indicate that the request should be handled asynchronously.

Line 13 actually initiates the request.

Example: using a timeout

You can use a timeout to prevent hanging your code forever while waiting for a read to occur. This is done by setting the value of the timeout property on the XMLHttpRequest object, as shown in the code below:

function loadFile (sURL, timeout, fCallback /*, argumentToPass1, argumentToPass2, etc. */) {
  var aPassArgs = Array.prototype.slice.call(arguments, 2), oReq = new XMLHttpRequest();
  oReq.ontimeout = function() {
    console.log("The request timed out.");
  }
  oReq.onreadystatechange = function() {
    if (oReq.readyState === 4) { 
      if (oReq.status === 200) {
        fCallback.apply(oReq, aPassArgs);
      } else {
        console.log("Error", oReq.statusText);
      }
    }
  };
  oReq.open("GET", sURL, true);
  oReq.timeout = timeout;
  oReq.send(null);
}

Notice the addition of code to handle the "timeout" event by setting the ontimeout handler.

Usage:

function showMessage (sMsg) {
  alert(sMsg + this.responseText);
}

loadFile("message.txt", 200, showMessage, "New message!\n");

Here, we're specifying a timeout of 200 ms.

{{ gecko_callout_heading("12.0") }}

Support for timeout was added in Gecko 12.0 {{ geckoRelease("12.0") }}.

Example: using asynchronous request avoiding closures

Manipulating the new XMLHttpRequest instance:

function switchXHRState() {
  switch (this.readyState) {
    case 0: console.log("open() has not been called yet."); break;
    case 1: console.log("send() has not been called yet."); break;
    case 2: console.log("send() has been called, headers and status are available."); break;
    case 3: console.log("Downloading, responseText holds the partial data."); break;
    case 4: console.log("Complete!"); this.callback.apply(this, this.arguments);
  }
};

function loadFile (sURL, fCallback /*, argumentToPass1, argumentToPass2, etc. */) {
  var oReq = new XMLHttpRequest();
  oReq.callback = fCallback;
  oReq.arguments = Array.prototype.slice.call(arguments, 2);
  oReq.onreadystatechange = switchXHRState;
  oReq.open("GET", sURL, true);
  oReq.send(null);
}

Using bind:

function switchXHRState(fCallback, aArguments) {
  switch (this.readyState) {
    case 0: console.log("open() has not been called yet."); break;
    case 1: console.log("send() has not been called yet."); break;
    case 2: console.log("send() has been called, headers and status are available."); break;
    case 3: console.log("Downloading, responseText holds the partial data."); break;
    case 4: console.log("Complete!"); fCallback.apply(this, aArguments);
  }
};

function loadFile (sURL, fCallback /*, argumentToPass1, argumentToPass2, etc. */) {
  var oReq = new XMLHttpRequest();
  oReq.onreadystatechange = switchXHRState.bind(oReq, fCallback, Array.prototype.slice.call(arguments, 2));
  oReq.open("GET", sURL, true);
  oReq.send(null);
}

Synchronous request

In rare cases, the use of a synchronous method is preferable to an asynchronous one.

Example: HTTP synchronous request

This example demonstrates how to make a simple synchronous request.

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

if (request.status === 200) {
  console.log(request.responseText);
}

Line 1 instantiates the XMLHttpRequest object.  Line 2 then opens a new request, specifying that a GET request will be used to fetch the Mozilla.org home page, and that the operation should not be asynchronous.

Line 3 sends the request.  The null parameter indicates that no body content is needed for the GET request.

Line 4 checks the status code after the transaction is completed.  If the result is 200 -- HTTP's "OK" result -- the document's text content is output to the console.

Example: Synchronous HTTP request from a Worker

One of the few cases in which a synchronous request is preferable to the asynchronous one is the use of XMLHttpRequest within a Worker.

example.html (the main page):

<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>MDN Example</title>
<script type="text/javascript">
  var oMyWorker = new Worker("myTask.js");  
  oMyWorker.onmessage = function(oEvent) {  
    alert("Worker said: " + oEvent.data);
  };

  oMyWorker.postMessage("Hello");
</script>
</head>
<body></body>
</html>

myFile.txt (the target of the synchronous XMLHttpRequest invocation):

Hello World!!

myTask.js (the Worker):

self.onmessage = function (oEvent) {
  if (oEvent.data === "Hello") {
    var oReq = new XMLHttpRequest();
    oReq.open("GET", "myFile.txt", false);  // synchronous request
    oReq.send(null);
    self.postMessage(oReq.responseText);
  }
};
Note: The effect, because of the use of the Worker, is however asynchronous.

It could be useful in order to interact in background with the server or to preload some content. See Using web workers for examples and details.

Irreplaceability of the synchronous use

There are some few cases in which the synchronous usage of XMLHttpRequest is not replaceable. This happens for example during the window.onunload and window.onbeforeunload events (see also below).

Sending the usual XMLHttpRequest when the page unloaded poses a problem with the asynchronous response from the server: by the time the response comes back, the page has unloaded and the callback function won’t exist anymore. This generates a JavaScript “function is not defined” error.

A possible solution is to make sure that any AJAX requests that you make on unload are make synchronously instead of asynchronously. This will ensure that the page doesn’t finish unloading before the server response comes back.

window.onbeforeunload = function () {
  var oReq = new XMLHttpRequest();
  oReq.open("GET", "logout.php?nick=" + escape(myName), false);  // synchronous request
  oReq.send(null);
  if (oReq.responseText.trim() !== "logout done"); {  // "logout done" is the expected response text
    return "Logout has failed. Do you want to complete it manually?";
  }
};

{{ languages( {"zh-cn": "zh-cn/DOM/XMLHttpRequest/Synchronous_and_Asynchronous_Requests" } ) }}

Revision Source

<p><code>XMLHttpRequest</code> supports both synchronous and asynchronous communications.</p>
<div class="note">
  <strong>Note:</strong> You shouldn't use synchronous <code>XMLHttpRequests</code> because, due to the inherently asynchronous nature of networking, there are various ways memory and events can leak when using synchronous requests. The only exception is that synchronous requests work well inside <a href="/en-US/docs/DOM/Using_web_workers" title="/en-US/docs/DOM/Using_web_workers">Workers</a>.</div>
<p>In versions of Firefox prior to Firefox 3, synchronous <code>XMLHttpRequest</code> requests blocked the user interface.&nbsp; In order to make it possible for the user to terminate frozen requests, Firefox 3 no longer does so.</p>
<h2 id="Asynchronous_request">Asynchronous request</h2>
<p>If you use <code>XMLHttpRequest</code> from an extension, you should use it asynchronously.&nbsp; In this case, you receive a callback when the data has been received, which lets the browser continue to work as normal while your request is being handled.</p>
<h3 id="Example.3A_send_a_file_to_the_console_log">Example: send a file to the console log</h3>
<p>This is the simplest usage of asynchronous <code>XMLHttpRequest</code>.</p>
<pre class="brush: js">
var oReq = new XMLHttpRequest();
oReq.open("GET", "<a class="external" href="http://www.mozilla.org/" rel="freelink">http://www.mozilla.org/</a>", true);
oReq.onreadystatechange = function (oEvent) {
&nbsp; if (oReq.readyState === 4) {
&nbsp;&nbsp;&nbsp; if (oReq.status === 200) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; console.log(oReq.responseText);
&nbsp;&nbsp;&nbsp; } else {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; console.log("Error", oReq.statusText);
&nbsp;&nbsp;&nbsp; }
&nbsp; }
};
oReq.send(null); </pre>
<p>Line 2 specifies <code>true</code> for its third parameter to indicate that the request should be handled asynchronously.</p>
<p>Line 3 creates an event handler function object and assigns it to the request's <code>onreadystatechange</code> attribute.&nbsp; This handler looks at the request's <code>readyState</code> to see if the transaction is complete in line 4, and if it is, and the HTTP&nbsp;status is 200, dumps the received content.&nbsp; If an error occurred, an error message is displayed.</p>
<p>Line 12 actually initiates the request.&nbsp; The callback routine is called whenever the state of the request changes.</p>
<h3 id="Example.3A_creating_a_standard_function_to_read_external_files">Example: creating a standard function to read external files</h3>
<p>In some cases you must read many external files. This is a standard function which uses the <code>XMLHttpRequest</code> object asynchronously in order to switch the content of the read file to a specified listener.</p>
<pre class="brush: js">
function loadFile (sURL, fCallback /*, argumentToPass1, argumentToPass2, etc. */) {
&nbsp; var aPassArgs = Array.prototype.slice.call(arguments, 2), oReq = new XMLHttpRequest();
&nbsp; oReq.onreadystatechange = function() {
&nbsp;&nbsp;&nbsp; if (oReq.readyState === 4) { 
&nbsp;&nbsp;&nbsp;   if (oReq.status === 200) {
&nbsp;&nbsp;&nbsp;     fCallback.apply(oReq, aPassArgs);
&nbsp;&nbsp;&nbsp;   } else {
&nbsp;&nbsp;&nbsp;     console.log("Error", oReq.statusText);
&nbsp;&nbsp;&nbsp;   }
&nbsp;&nbsp;&nbsp; }
&nbsp; };
&nbsp; oReq.open("GET", sURL, true);
&nbsp; oReq.send(null);
}
</pre>
<p>Usage:</p>
<pre class="brush: js">
function showMessage (sMsg) {
&nbsp; alert(sMsg + this.responseText);
}

loadFile("message.txt", showMessage, "New message!\n");
</pre>
<p>Line 1 declares a function which will pass all arguments after the third to the <code>fCallback</code> function when the file has been loaded.</p>
<p>Line 3 creates an event handler function object and assigns it to the request's <code>onreadystatechange</code> attribute.&nbsp; This handler looks at the request's <code>readyState</code> to see if the transaction is complete in line 4, and if it is, and the HTTP&nbsp;status is 200, calls the callback function.&nbsp; If an error occurred, an error message is displayed.</p>
<p>Line 12 specifies <code>true</code> for its third parameter to indicate that the request should be handled asynchronously.</p>
<p>Line 13 actually initiates the request.</p>
<h3 id="Example.3A_using_a_timeout">Example: using a timeout</h3>
<p>You can use a timeout to prevent hanging your code forever while waiting for a read to occur. This is done by setting the value of the <code>timeout</code> property on the <code>XMLHttpRequest</code> object, as shown in the code below:</p>
<pre class="brush: js">
function loadFile (sURL, timeout, fCallback /*, argumentToPass1, argumentToPass2, etc. */) {
&nbsp; var aPassArgs = Array.prototype.slice.call(arguments, 2), oReq = new XMLHttpRequest();
&nbsp; oReq.ontimeout = function() {
&nbsp; &nbsp; console.log("The request timed out.");
&nbsp; }
&nbsp; oReq.onreadystatechange = function() {
&nbsp;&nbsp;&nbsp; if (oReq.readyState === 4) { 
&nbsp;&nbsp;&nbsp;   if (oReq.status === 200) {
&nbsp;&nbsp;&nbsp;     fCallback.apply(oReq, aPassArgs);
&nbsp;&nbsp;&nbsp;   } else {
&nbsp;&nbsp;&nbsp;     console.log("Error", oReq.statusText);
&nbsp;&nbsp;&nbsp;   }
&nbsp;&nbsp;&nbsp; }
&nbsp; };
&nbsp; oReq.open("GET", sURL, true);
&nbsp; oReq.timeout = timeout;
&nbsp; oReq.send(null);
}
</pre>
<p>Notice the addition of code to handle the "timeout" event by setting the <code>ontimeout</code> handler.</p>
<p>Usage:</p>
<pre class="brush: js">
function showMessage (sMsg) {
&nbsp; alert(sMsg + this.responseText);
}

loadFile("message.txt", 200, showMessage, "New message!\n");
</pre>
<p>Here, we're specifying a timeout of 200 ms.</p>
<div class="geckoVersionNote" style="undefined">
  <p>{{ gecko_callout_heading("12.0") }}</p>
  <p>Support for <code>timeout</code> was added in Gecko 12.0 {{ geckoRelease("12.0") }}.</p>
</div>
<h3 id="Example.3A_using_asynchronous_request_avoiding_closures">Example: using asynchronous request avoiding closures</h3>
<p>Manipulating the new <code>XMLHttpRequest</code> instance:</p>
<pre class="brush: js">
function switchXHRState() {
&nbsp; switch (this.readyState) {
&nbsp;&nbsp; &nbsp;case 0: console.log("open() has not been called yet."); break;
&nbsp;&nbsp; &nbsp;case 1: console.log("send() has not been called yet."); break;
&nbsp;&nbsp; &nbsp;case 2: console.log("send() has been called, headers and status are available."); break;
&nbsp;&nbsp; &nbsp;case 3: console.log("Downloading, responseText holds the partial data."); break;
&nbsp;&nbsp; &nbsp;case 4: console.log("Complete!"); this.callback.apply(this, this.arguments);
&nbsp; }
};

function loadFile (sURL, fCallback /*, argumentToPass1, argumentToPass2, etc. */) {
&nbsp; var oReq = new XMLHttpRequest();
&nbsp; oReq.callback = fCallback;
&nbsp; oReq.arguments = Array.prototype.slice.call(arguments, 2);
&nbsp; oReq.onreadystatechange = switchXHRState;
&nbsp; oReq.open("GET", sURL, true);
&nbsp; oReq.send(null);
}
</pre>
<p>Using <code><a href="/en/JavaScript/Reference/Global_Objects/Function/bind" title="/en/JavaScript/Reference/Global_Objects/Function/bind">bind</a></code>:</p>
<pre class="brush: js">
function switchXHRState(fCallback, aArguments) {
&nbsp; switch (this.readyState) {
&nbsp;&nbsp;&nbsp; case 0: console.log("open() has not been called yet."); break;
&nbsp;&nbsp;&nbsp; case 1: console.log("send() has not been called yet."); break;
&nbsp;&nbsp;&nbsp; case 2: console.log("send() has been called, headers and status are available."); break;
&nbsp;&nbsp;&nbsp; case 3: console.log("Downloading, responseText holds the partial data."); break;
&nbsp;&nbsp;&nbsp; case 4: console.log("Complete!"); fCallback.apply(this, aArguments);
&nbsp; }
};

function loadFile (sURL, fCallback /*, argumentToPass1, argumentToPass2, etc. */) {
&nbsp; var oReq = new XMLHttpRequest();
&nbsp; oReq.onreadystatechange = switchXHRState.bind(oReq, fCallback, Array.prototype.slice.call(arguments, 2));
&nbsp; oReq.open("GET", sURL, true);
&nbsp; oReq.send(null);
}
</pre>
<h2 id="Synchronous_request">Synchronous request</h2>
<p>In rare cases, the use of a synchronous method is preferable to an asynchronous one.</p>
<h3 id="Example.3A_HTTP_synchronous_request">Example: HTTP synchronous request</h3>
<p>This example demonstrates how to make a simple synchronous request.</p>
<pre class="brush: js">
var request = new XMLHttpRequest();
request.open('GET', 'http://www.mozilla.org/', false); 
request.send(null);

if (request.status === 200) {
  console.log(request.responseText);
}
</pre>
<p>Line 1 instantiates the <code>XMLHttpRequest</code> object.&nbsp; Line 2 then opens a new request, specifying that a <code>GET</code> request will be used to fetch the Mozilla.org home page, and that the operation should not be asynchronous.</p>
<p>Line 3 sends the request.&nbsp; The <code>null</code> parameter indicates that no body content is needed for the <code>GET</code> request.</p>
<p>Line 4 checks the status code after the transaction is completed.&nbsp; If the result is 200 -- HTTP's "OK" result -- the document's text content is output to the console.</p>
<h3 id="Example.3A_Synchronous_HTTP_request_from_a_Worker">Example: Synchronous HTTP request from a <code>Worker</code></h3>
<p>One of the few cases in which a synchronous request is preferable to the asynchronous one is the use of <code>XMLHttpRequest</code> within a <code><a href="/en/DOM/Worker" title="/en/DOM/Worker">Worker</a></code>.</p>
<p><code><strong>example.html</strong></code> (the main page):</p>
<pre class="brush: html">
&lt;!doctype html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /&gt;
&lt;title&gt;MDN Example&lt;/title&gt;
&lt;script type="text/javascript"&gt;
  var oMyWorker = new Worker("myTask.js"); &nbsp;
  oMyWorker.onmessage = function(oEvent) { &nbsp;
&nbsp;   alert("Worker said: " + oEvent.data);
  };

  oMyWorker.postMessage("Hello");
&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;&lt;/body&gt;
&lt;/html&gt;
</pre>
<p><code><strong>myFile.txt</strong></code> (the target of the synchronous <code><a href="/en/DOM/XMLHttpRequest" title="/en/XMLHttpRequest">XMLHttpRequest</a></code> invocation):</p>
<pre>
Hello World!!
</pre>
<p><code><strong>myTask.js</strong></code> (the <code><a href="/en/DOM/Worker" title="/en/DOM/Worker">Worker</a></code>):</p>
<pre class="brush: js">
self.onmessage = function (oEvent) {
&nbsp; if (oEvent.data === "Hello") {
&nbsp;&nbsp;&nbsp; var oReq = new XMLHttpRequest();
&nbsp;&nbsp;&nbsp; oReq.open("GET", "myFile.txt", false);  // synchronous request
&nbsp;&nbsp;&nbsp; oReq.send(null);
&nbsp;&nbsp;&nbsp; self.postMessage(oReq.responseText);
&nbsp; }
};
</pre>
<div class="note">
  <strong>Note:</strong> The effect, because of the use of the <code>Worker</code>, is however asynchronous.</div>
<p>It could be useful in order to interact in background with the server or to preload some content. See <a class="internal" href="/En/DOM/Using_web_workers" title="en/Using DOM workers">Using web workers</a> for examples and details.</p>
<h3 id="Irreplaceability_of_the_synchronous_use">Irreplaceability of the synchronous use</h3>
<p>There are some few cases in which the synchronous usage of XMLHttpRequest is not replaceable. This happens for example during the <a class="internal" href="/en/DOM/window.onunload" title="en/DOM/window.onunload"><code>window.onunload</code></a> and <a class="internal" href="/en/DOM/window.onbeforeunload" title="en/DOM/window.onbeforeunload"><code>window.onbeforeunload</code></a> events (<a class="internal" href="#XMLHttpRequests_being_stopped" title="en/XMLHttpRequest/Using_XMLHttpRequest#XMLHttpRequests_being_stopped">see also below</a>).</p>
<p>Sending the usual XMLHttpRequest when the page unloaded poses a problem with the asynchronous response from the server: by the time the response comes back, the page has unloaded and the callback function won’t exist anymore. This generates a JavaScript “function is not defined” error.</p>
<p style="text-align: center;"><img alt="" class="internal" src="/@api/deki/files/6227/=AsyncUnload.jpg" style="width: 467px; height: 359px;" /></p>
<p>A possible solution is to make sure that any AJAX requests that you make on unload are make synchronously instead of asynchronously. This will ensure that the page doesn’t finish unloading before the server response comes back.</p>
<pre class="brush: js">
window.onbeforeunload = function () {
&nbsp; var oReq = new XMLHttpRequest();
&nbsp; oReq.open("GET", "logout.php?nick=" + escape(myName), false);&nbsp; // synchronous request
&nbsp; oReq.send(null);
&nbsp; if (oReq.responseText.trim() !== "logout done"); {&nbsp; // "logout done" is the expected response text
&nbsp;&nbsp;&nbsp; return "Logout has failed. Do you want to complete it manually?";
&nbsp; }
};
</pre>
<p>{{ languages( {"zh-cn": "zh-cn/DOM/XMLHttpRequest/Synchronous_and_Asynchronous_Requests" } ) }}</p>
Revert to this revision