How to Create an XMLHttpRequest Object

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

  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 Minnick, the co-founder of WatzThis?, has overseen the development of hundreds of web and mobile projects for customers from small businesses to some of the world’s largest companies. A prolific writer, Chris has authored and co-authored books and articles on a wide range of Internet-related topics including HTML, CSS, mobile apps, e-commerce, e-business, Web design, XML, and application servers. His published books include Adventures in Coding, JavaScript For Kids For Dummies, Writing Computer Code, Coding with JavaScript For Dummies, Beginning HTML5 and CSS3 For Dummies, Webkit For Dummies, CIW E-Commerce Designer Certification Bible, and XHTML.

About Webucator

Webucator provides instructor-led training to students throughout the US and Canada. We have trained over 90,000 students from over 16,000 organizations on technologies such as Microsoft ASP.NET, Microsoft Office, Azure, Windows, Java, Adobe, Python, SQL, JavaScript, Angular and much more. Check out our complete course catalog.