Basics of AJAX

Welcome to the next article where we will discuss the basics of this, what changed JavaScript for ever.

Basics of AJAX

The AJAX (Asynchronous JavaScript and XML) — is a technology of web application development, in which the user can interact with the server without reloading the entire document. Operations are done asynchronously.

AJAX technology consists of several elements:

– XMLHttpRequest — an object allowing asynchronous transmission of data over the network. During processing the user can perform other tasks, also retrieve data from multiple sources.

– JavaScript — the language well known to us, although in the assumption it could be a different client-side language with DOM support, e.g. VBScript.

– XML  — markup language as data carrier of sent and/or received information. In addition to the XML also other formats are used, such as JSON, although the data carrier can also be plain text or HTML snippets. For the Ajax with JSON there is even a special term: AJAJ.

Practical AJAX

Below we presented a basic example of using AJAX. Classical, in pure JavaScript i.e. without frameworks.

var httpRequest;
if (window.XMLHttpRequest) { // Mozilla, Safari, …
    httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
    httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}

httpRequest = new XMLHttpRequest();
httpRequest.overrideMimeType('text/xml');

// define a getter function:
httpRequest.onreadystatechange = name;

// or another way:
httpRequest.onreadystatechange = function() {
    // definition
    alert('Test');
};

The open() method:

// true in the 3rd parameter = the request is asynchronous
httpRequest.open('GET', 'http://www.example.org/some.file', true);

Examples of using the open() method:

r.open('GET', 'mysite.jsp', true);
r.open('GET', 'myfile.jpg', true);
r.open('GET', 'http://www.example.net/get.php?id=123', true);

Sending the data — send():

httpRequest.send(null);

The send() method has one parameter: data appended to the query. This parameter must be used for the POST method. We use null if the method used is GET.

If you want to send data using the POST method, you should change MIME of the request:

httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

Capturing of reaction — callback

And here we go with the magic! It’s time to operate on the document and perform changes without reloading the page.

Example — a callback:

if (httpRequest.readyState == 4) {
    // everything OK, data received
    alert('OK');
} else {
    // not ready yet
    alert('Please wait…');
}

We check the state by comparing the value.

List of values for readyState:

0 — (uninitialized)
1 — (loading)
2 — (loaded)
3 — (interactive)
4 — (complete)

if (httpRequest.status == 200) {
    // ok
} else {
    // a problem, e.g. Error 404 or Error 500
}

Working with XML

This example shows how to parse XML simple structure that serves as an information carrier.

<?xml version="1.0" ?>
<root>
  Test data
</root>

// … AJAX initialization (shown above) …
makeRequest('test.xml');
// …

var xmldoc = httpRequest.responseXML;
var root_node = xmldoc.getElementsByTagName('root').item(0);
alert(root_node.firstChild.data);

The XMLHTTPRequest object

Let’s see what the XMLHTTPRequest object hides.

Methods:

abort() — cancels the current request

getAllResponseHeaders() — returns a complete set of HTTP headers as a string

getResponseHeader( headerName ) — returns the value of a specific HTTP header

Bankruptcy lawyer Loveland texas bankruptcy loomisgreene.com.

open( method, URL ) — specifies the method, URL, and other optional arguments of the request

open( method, URL, async ) — ‘async’ is a logical value to specify the mode (synchronous / asynchronous)

open( method, URL, async, userName )

open( method, URL, async, userName, password )  — the ‘method’ argument may have a value: “GET”, “POST”, “HEAD”, “PUT”, “DELETE” or other HTTP methods listed in the W3C specification

The URL argument can be either relative or absolute address.

The “async” argument determines whether the request should be processed synchronously or not. For value of 1 (true) the script will continue work after the send() method call, for value of 0 (false) the script will be processed after receiving the response.

send( content )  — sends a request

setRequestHeader( headerName, headerContent )  — adds a pair of header / content to HTTP requests

 

Properties of the XMLHTTPRequest object:

onreadystatechange — specifies a reference to the function performed at each change of the readyState

readyState  — contains the status of the object, as follows:

0 = uninitialized
1 = open
2 = request sent
3 = receiving a response
4 = request completed — ready

responseText — contains the answer as text

responseXML — contains the answer as XML; this property returns XML document that can be parsed using the classes and interfaces of the W3C DOM

status  — contains the HTTP response code as a number (404, 200, etc)

statusText  — contains the status as a string (e.g. “Not Found” or “OK”).

Example — XML processing:

<?xml version="1.0" encoding=" utf-8"?>
<bookList xmlns="http://site1.com" xmlns:pub="http://site2.com">
  <book isbn="011111111">
    <title>Ajax. Programming.</title>
    <author>John Doe, Evan Brown</author>
    <pub:name>Coder Publishing</pub:name>
  </book>
  <book isbn="022222222">
    <title>JS Coding for Geeks</title>
    <author>Fred Al Fred</author>
    <pub:name>Xorw</pub:name>
  </book>
</bookList>

Getting the data — example of using XPath:


var sNameSpace = "xmlns:na='http://site1.com' xmlns:pub='http://site2.com'";
oXmlDom.setProperty("SelectionNamespaces", sNameSpace);

var oRoot = oXmlDom.documentElement;
var sXPath = "na:book/pub:name";
var cPublishers = oRoot.selectNodes(sXPath);

if (cPublishers.length < 0) {
    alert(cPublishers.length + " <pub:name/> elements found with "
            + sXPath);
}

Summary

AJAX is a very vast subject. Today it is ubiquitous, but I remember those times when this technology freshly became popular, and what impression could be done by the effects based on AJAX.

Soon we will describe JavaScript frameworks, which containing also support for AJAX programming. And this is great, because the programmer can easily create the final result, without going into details of the XMLHTTPRequest (as we did today).

My favorite solutions are those offered by jQuery.

We strongly encourage you to follow the subsequent entries.