How to Create an XMLHttpRequest Object

  • google plus

In Brief...

XMLHttpRequest is the mechanism for sending data to and retrieving data from the server with Ajax.

Take our Ajax Training course for free.

See the Course Outline and Register


  1. Use the XMLHttpRequest() constructor to create the object, as shown here:
    var xmlhttp = newXMLHttpRequest();
  2. Use the XMLHttpRequest object in an HTML document, as shown here:
    <meta charset="UTF-8">
    <script type="text/javascript" src="lib.js"></script>
    <script type="text/javascript">
     function start() {
         if (window.XMLHttpRequest) {
             var xmlhttp = new XMLHttpRequest();
             document.getElementById("Content").innerHTML =
                     "<h1>Using XMLHttpRequest Object</h1>";
         } else {
             var xmlhttp = false;
             document.getElementById("Content").innerHTML =
                     "<h1>XMLHttp cannot be created!</h1>";
     observeEvent(window, "load", function() {
         var btn = document.getElementById("btnStart");
         observeEvent(btn, "click", start);
    <title>XMLHttpRequest - HTML5 Method</title>
     <button id="btnStart">Start</button>
     <div id="Content"></div>

    Code Explanation: This code attempts to create an XMLHttpRequest object using the XMLHttpRequest() constructor. If it succeeds, it writes out "Using XMLHttpRequest Object" to the body of the page. If it fails, it writes out "XMLHttp cannot be created!"

Author: Chris Minnick

Chris is a prolific author and trainer, and the CEO of WatzThis?. His published books include Writing Computer Code, JavaScript for Kids, Coding with JavaScript For Dummies, Beginning HTML5 and CSS3 For Dummies, Webkit For Dummies, CIW eCommerce Certification Bible, and New Riders' XHTML.