Home > Articles > Open Source > Ajax & JavaScript

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Sending a Synchronous Request

XMLHttp.open("GET", "phrasebook.txt", false);

By default, HTTP requests via XMLHttpRequest are asynchronous, which explains the need for a callback function. However, when you set the third parameter of the open() method to false, the request is a synchronous one, which means that the script execution is stopped until data comes back from the server. The following code makes use of that:

Sending a Synchronous Request (xmlhttpsync.html)

<script language="JavaScript"
  type="text/javascript" src="xmlhttp.js"></script>
<script language="JavaScript"
  type="text/javascript">
window.onload = function() {
  var XMLHttp = getXMLHttp();
  XMLHttp.open("GET", "phrasebook.txt", false);
  XMLHttp.send(null);
  document.getElementById("output").innerHTML =
    "Returned data: " + XMLHttp.responseText;
}
</script>
<p id="output">Calling the server ...</p>

Note that the whole code is executed only after the full page has been loaded; otherwise, the access to the output HTML element may fail.

  • + Share This
  • 🔖 Save To Your Account