DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones Build AI Agents That Are Ready for Production
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
Build AI Agents That Are Ready for Production

Just dropped: New 2026 “Cloud-Native Foundations” Trend Report. See how teams are tackling complexity, cost & reliability.

AI can investigate. Engineers still decide. See how both work together across incident response in this DZone + Datadog webinar on Oct. 29.

  1. DZone
  2. Refcards
  3. Getting Started with Ajax
refcard cover
Refcard #002

Getting Started with Ajax

Unlocking Unobtrusive JavaScript

Introduces Ajax, a group interrelated techniques used in client-side web development for creating asynchronous web applications.

Free PDF for Easy Reference
refcard cover

Written By

author avatar Dave Crane
Snr Developer, Sunwheel
Table of Contents
► Getting Started ► Getting to Know HTTP ► Tips for Using XHR ► Ajax and Architecture ► Ajax Toolkits ► General JavaScript Programming Tips ► Widgets vs. Behaviors ► Tools of the Trade
Section 1

Getting Started

By Dave Crane

The standard way to do Ajax is to use the XMLHttpRequest object, known as XHR by its friends. Use XHR directly, or via one of the helpful Ajax libraries such as Prototype or jQuery. How do we use XHR "by hand"? To start with, we need to get a reference to it:

if (window.XMLHttpRequest) {
    xhr = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
  }

We can then open a connection to a URL:

xhr.open(
    "GET",
    "my-dynamic-content.jsp?id="
    +encodeURI(myId),
    true
  );

Specify a callback function to receive the response:

xhr.onreadystatechange = function(){
    processReqChange(req);
  }

and then send the request:

xhr.send(null);

The server may be busy, or the network may be slow. We don't want to sit around doing nothing until the response arrives, and because we've assigned the callback function, we don't have to. That's the five-minute guide for the impatient. For those who like to know the details, we've listed the fuller details of the XHR object below.

Method Name Parameters and Descriptions
open(method, url, async) open a connection to a URL method = HTTP verb (GET, POST, etc.) url = url to open, may include querystring async = whether to make asynchronous request
onreadystatechange assign a function object as callback (similar to onclick, onload, etc. in browser event model)
setRequestHeader (namevalue) add a header to the HTTP request
send(body) send the request body = string to be used as request body
abort() stop the XHR from listening for the response
readyState stage in lifecycle of response (only populated after send() is called)
httpStatus The HTTP return code (integer, only populated after response reaches the loaded state)
responseText body of response as a JavaScript string (only set after response reaches the interactive readyState)
responseXML body of the response as a XML document object (only set after response reaches the interactive readyState)
getResponseHeader (name) read a response header by name
getAllResponseHeaders() Get an array of all response header names
Section 2

Getting to Know HTTP

To make use of the XHR to its fullest, we recommend you become familiar with the workings of the HTTP protocol. Using Ajax, you have much more control over HTTP than with classic web app development.

Request and Response Diagram

HTTP is a stateless request-response protocol.

  • Both request and response contain headers and an optional body, which is free text.
  • Only a POST request contains a body.
  • A request defines a verb or method.
  • The Mime type of request and response can be set by the header Content-type

Common HTTP Verbs

99% of the time, you'll only need GET and POST. Many other verbs are used by WebDAV, Subversion over HTTP, and other niche applications, but not all web servers will understand them.

Verb Notes
GET Strictly speaking, should be used only to fetch data, not to effect changes on the server. GET requests contain no body. Parameters are passed in the querystring of the URL.
POST Should be used to update data on the server. Parameters/data passed in the body.
HEAD Will fetch the headers of the response only, not the body. Useful for finding out how large a resource is (read the Content-length header) or how old it is (read the Last-modified header), for example.

If you're using the increasingly popular REST approach to web services, the HTTP verb is used to indicate the type of operation being performed. The most commonly used HTTP verbs in REST map onto the CRUD (create, read, update, delete) approach:

HTTP Verb CRUD operation Notes
PUT Create Add a new object instance to the domain model.
GET Read Get an existing domain object from the server.
POST Update Modify an existing domain object.
DELETE Delete Remove an existing object from the domain model.

Common Mime Types

Setting the right mime type for your request and response is good manners it's also vital to get the app to behave correctly!

Mime Type Meaning Usage
application/x-www-form-urlencoded Body is an encoded querystring of key-value pairs Sending request from HTML form or Ajax. Required in order for server to decode parameters into $_GET, servlet parameters, or HttpRequest.Form.
text/xml, application/xml Body is an XML document Can be used anywhere ' request or response. Must set response to one of these in order to use XHR.responseXML property.
text/plain Body is plain unformatted text  
text/html, text/xhtml Body is (X)HTML content Standard web pages sent from server, or content fragments sent to Ajax apps.
text/javascript Body is a piece of JavaScript code Standard .js files, JavaScript fragments sent to Ajax apps.
image/png, image/jpeg, image/gif Body is a binary image Images sent by server.
Section 3

Tips for Using XHR

  • Always set async to true when calling open(). Synchronous Ajax requests block the browser UI, giving the stop-start behaviour we were trying to get away from in the first place!
  • XHR can be fussy about order of setting-up. Always set the callback handler before calling send()
  • To send HTML-form like data
    • Use encodeURI() to encode all data values
    • Set the mime-type of the request to application/x-www- form-urlencoded
  • Set the response mime type to application/xml or text/xml if you want to use the responseXML property

Handling the Response

We've assigned a callback handler function to our XHR object. This function will get called several times as the response comes in. Typically, we only want to parse the response once it has fully arrived, i.e. the readyState is complete.

xhr.onreadystatechange=function(){
    if (xhr.readyState==4){
      if (xhr.status==200){
        parseResponse(xhr);
      }else{
        //handle the HTTP error...
      }
    };
  };

XHR ReadyState Values

State Value Comments
0 Uninitialized The request hasn't yet been sent
1 Loading The response hasn't yet arrived
2 Loaded Response headers can be read
3 Interactive Response body is incomplete, but can be read
4 Complete Response body is complete

So, what might the parseResponse() method look like? We have a lot of freedom in the types of response we send. Let's look at some of the common ones.

Handling a HTML Response

The server can send pre-assembled HTML content, which we just stitch into the web page.


The Moon on a Stick
What every project manager wants - and they want it yesterday!

NB: Stick not included.
$365.00


function parseResponse(xhr){
  var div=document
    .getElementById("myDiv");
  div.innerHTML=xhr.responseText;
}

Handling a JSON Response

JSON is a simple text-markup that's extremely easy for JavaScript to digest! It doesn't come so naturally to server-side languages, but there are JSON libraries for most servers these days'see http://www.json.org. Most Ajax libraries now provide support for JSON.

{
  imgSrc: "kmoon.png",
  title: "The Moon on a Stick",
  description: "What every project manager wants 
        - and they want it yesterday!

NB: Stick not included.", price: "365.00" }

function parseResponse(xhr){
  var jsonObj=eval(
   "("
   +xhr.responseText
   +")"
  );
  setImgSrc(jsonObj.imgSrc);
  setTitle(jsonObj.title);
}

Handling an XML Response

XML is a more natural fit for most server technologies. XHR supports XML by giving us the responseXML property, but parsing this using the DOM is hard work.



  The Moon on a Stick
  
NB: Stick not included.]]>


function parseResponse(xhr){
  var xmlDoc=xhr.responseXML;
  var item=xmlDoc.getElementsByTagName('item')[0];
  var imgSrc=item.getAttribute('imgSrc');
  var title=item.getElementsByTagName('title')[0]
    .firstChild.data;
  setImgSrc(imgSrc);
  setTitle(title);
}

Some browsers also support XPath as a more pleasant way to parse XML. Sarissa and mozXPath.js both provide cross-browser XPath support.



  The Moon on a Stick
  
NB: Stick not included.]]>


function parseResponse(xhr){
  var xmlDoc=xhr.responseXML;
  var imgSrc=xmlDoc.selectSingleNode('/item/@imgSrc').value;
  var title=xmlDoc.selectSingleNode
          ('/item/title/text()').value;
  setImgSrc(imgSrc);
  setTitle(title);
}

Handling a JavaScript Response

Another approach to Ajax is to generate scripts on the server, and send them to the client to be evaluated. Care should be taken here to define a suitably high-level API on the client against which the generated script is to run, otherwise tight coupling between server and client code can result.


setImgSrc("kmoon.png");
setTitle("The Moon on a Stick");


function parseResponse(xhr){
  eval(xhr.responseText);
}

Handling Mixed Responses

Some Javascript libraries allow mixing of these dialects of Ajax within a single response. The Prototype Ajax.Updater, for example, can accept a response as HTML, into which