SHARE
Facebook X Pinterest WhatsApp

How to Develop Web Applications with Ajax: Part 1

Aug 26, 2008

In the past, web applications were limited because a web page had to be reloaded (or another page loaded in its place) in order for new data to be obtained. Other methods were available (without loading another page), but the techniques weren’t well supported and had a tendency to be buggy. In recent months, a technique that had not been widely supported in the past has become available to a large number of web surfers, giving developers more freedom to develop cutting-edge web applications. These applications, which asynchronously retrieve XML data via JavaScript, are affectionately known as “Ajax applications” (Asynchronous Javascript and XML applications). In this article, I will explain how to retrieve a remote XML file via Ajax to update a web page, and as this series continues, I will discuss more ways that Ajax technology can be used to take your web applications to the next level.


The first step is to create an XML file with some data. We’ll call this file data.xml. It’s a simple XML file and would most certainly be more complex in a real-world application, but for clarity our examples will be simple and concise.






<?xml version=”1.0″ encoding=”UTF-8″?>
<root>
  <data>
    This is some sample data. It is stored in an XML file and retrieved by JavaScript.
  </data>
</root>


Now let’s create a simple web page containing some sample data. This is the page that all our JavaScript will be in, and the page that users will visit to see the Ajax script in action. Let’s call this file ajax.html.






<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01//EN”
  “http://www.w3.org/TR/html4/strict.dtd”>
<html lang=”en” dir=”ltr”>
  <head>
    <meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1″>
    <title>Developing Web Applications with Ajax – Example</title>
  </head>
  <body>
    <h1>Developing Web Applications with Ajax</h1>
    <p>This page demonstrates the use of Asynchronous Javascript and XML (Ajax) technology to
    update a web page’s content by reading from a remote file dynamically — no page reloading
    is required. Note that this operation does not work for users without JavaScript enabled.</p>
    <p id=”xmlObj”>
    This is some sample data. It is the default data for this web page. <a href=”data.xml”
    title=”View the XML data.” onclick=”ajaxRead(‘data.xml’); this.style.display=’none’; return false”>View XML     data.</a>
    </p>
  </body>
</html>


Note that we link to the data.xml file for users without JavaScript. For users with JavaScript, the function “ajaxRead” is called, the link is hidden, and the link does not redirect to the data.xml file. The function “ajaxRead” isn’t defined yet, so if you test the example code above, you’ll get a JavaScript error. Let’s go ahead and define that function (and another) so you can see how Ajax works. The following SCRIPT goes in your HEAD tags:



<script type=”text/javascript”><!–
function ajaxRead(file){
  var xmlObj = null;
  if(window.XMLHttpRequest){
      xmlObj = new XMLHttpRequest();
  } else if(window.ActiveXObject){
      xmlObj = new ActiveXObject(“Microsoft.XMLHTTP”);
  } else {
      return;
  }
  xmlObj.onreadystatechange = function(){
    if(xmlObj.readyState == 4){
       updateObj(‘xmlObj’, xmlObj.responseXML.getElementsByTagName(‘data’)[0].firstChild.data);
     }
    }
    xmlObj.open (‘GET’, file, true);
    xmlObj.send (”);
  }
  function updateObj(obj, data){
   document.getElementById(obj).firstChild.data = data;
  }
  //–></script>


That’s quite a bit, so let’s take this one piece at a time. The first function is “ajaxRead” – what we call from our “View XML data” link on the web page. In the function, we define an “xmlObj” variable – this will be the middleman between the client (user viewing the web page) and the server (the web site itself). We define this object in an if/else chunk:



if(window.XMLHttpRequest){
   xmlObj = new XMLHttpRequest();
} else if(window.ActiveXObject){
   xmlObj = new ActiveXObject(“Microsoft.XMLHTTP”);
} else {
   return;
}


This is just a test for the availability of different objects – some browsers implement the XMLHttpRequest object differently, so when we define “xmlObj” as our XMLHttpRequest object, we have to define it depending on what browser implementation is available. If no XMLHttpRequest object is available, we end the function with a “return” statement to avoid errors. Most of the time, this check will return an XMLHttpRequest object – this particular code should work in almost every browser out there, with the exception of some older browsers (it works in IE 5.01, but will cease to function in Netscape 4).


Next is this block:



xmlObj.onreadystatechange = function(){
  if(xmlObj.readyState == 4){
      updateObj(‘xmlObj’, xmlObj.responseXML.getElementsByTagName(‘data’)[0].firstChild.data);
  }
}

Recommended for you...

The Revolutionary ES6 Rest and Spread Operators
Rob Gravelle
Aug 23, 2022
Ahead of Time (AOT) Compilation in Angular
Tariq Siddiqui
Aug 16, 2022
Converting a JavaScript Object to a String
Rob Gravelle
Aug 14, 2022
Understanding Primitive Type Coercion in JavaScript
Rob Gravelle
Jul 28, 2022
HTML Goodies Logo

The original home of HTML tutorials. HTMLGoodies is a website dedicated to publishing tutorials that cover every aspect of being a web developer. We cover programming and web development tutorials on languages and technologies such as HTML, JavaScript, and CSS. In addition, our articles cover web frameworks like Angular and React.JS, as well as popular Content Management Systems (CMS) that include WordPress, Drupal, and Joomla. Website development platforms like Shopify, Squarespace, and Wix are also featured. Topics related to solid web design and Internet Marketing also find a home on HTMLGoodies, as we discuss UX/UI Design, Search Engine Optimization (SEO), and web dev best practices.

Property of TechnologyAdvice. © 2025 TechnologyAdvice. All Rights Reserved

Advertiser Disclosure: Some of the products that appear on this site are from companies from which TechnologyAdvice receives compensation. This compensation may impact how and where products appear on this site including, for example, the order in which they appear. TechnologyAdvice does not include all companies or all types of products available in the marketplace.