AJAX Tutorial
AJAX stands for Asynchronous Java And XML. AJAX can be a great tool for adding responsiveness and functionality to a web page.
First up, here are some examples showing the AJAX script from this page in use.
- Simple AJAX Demo - Retrieves a file and displays the contents in an alert box.
- AJAX Demo App - Gets the contents of a textarea and sends it to the server. The server returns a HTML snippet which is added to the page.
- XML AJAX Demo - Retrieves an XML document and uses the contents to update the page.
Using the AJAX Script
Sending and handling AJAX requests is easy if you use this script. It supplies the functions listed below.
Function - ajaxSend()
The main function provided by this script is ajaxSend(method, url, parameters, responseHandler, asynchronous). The first two parameters of this function are compulsory parameters and the last three are optional parameters.
Parameters
- method (compulsory) - The send method for the request (post/get).
- url (compulsory) - The url the request will be sent to.
- parameters (default:none) - Any parameters to be sent with the request.
- responseHandler (default:none) - The function that request will be passed to once a response is received.
- asynchronous (default:true) - Whether the request will be asynchronous or not (true/false).
Returns
Nothing
Function - getXMLEntries()
A helper method to quickly get the value from bottom level nodes in a usable format.
Parameters
- xmlBranch (compulsory) - The xml branch to search.
- tagName (compulsory) - The name of the tag to search for.
Returns
An array strings containing the data in the specified element(s).
Function - getXMLData()
A helper method to quickly get the value from a bottom level node.
Parameters
- xmlNode (compulsory) - The node to extract the data from.
Returns
An string containing the data in the node.
The code
/*==============================================================
Copyright 2006
Dynamic-Tools.net
Do not remove this header.
Script: Dynamic-Tools AJAX Toolkit
Description: This script simplifies sending AJAX requests and
handling the responses to those requests. The
requests are threadsafe so you can send off as
many at a time as you like.
Author: Peter Wilkinson
==============================================================*/
// send a threadsafe XMLHTTPRequest
function ajaxSend(method, url, parameters, responseHandler, asynchronous)
{
if (typeof method != 'string')
{
alert("Invalid request method.");
return false;
}
method = method.toUpperCase();
if (method != 'POST' && method != 'GET')
{
alert("Invalid request method.");
return false;
}
if (typeof parameters != 'string') parameters = '';
if (typeof asynchronous == 'undefined') asynchronous = true;
// build the request
var ajaxRequest = null;
if (window.XMLHttpRequest) ajaxRequest = new XMLHttpRequest();
else if (window.ActiveXObject) ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
// bind the callback.
function ajaxBindCallback()
{
if (ajaxRequest.readyState == 4)
{
if (ajaxRequest.status == 200)
{
if (responseHandler) responseHandler(ajaxRequest);
}
else
{
if (ajaxRequest.status == 404)
{
alert("The requested service could not be found.");
}
else
{
alert("There was a problem retrieving the xml data:\n"
+ ajaxRequest.status + ":\t"
+ ajaxRequest.statusText + "\n"
+ ajaxRequest.responseText);
}
}
}
}
// send the request
if (ajaxRequest)
{
if (asynchronous) ajaxRequest.onreadystatechange = ajaxBindCallback;
if (method == "GET")
{
url = url + '?' + parameters
parameters = null;
}
ajaxRequest.open(method, url, asynchronous);
if (method == 'POST')
{
ajaxRequest.setRequestHeader('Content-Type',
'application/x-www-form-urlencoded; charset=UTF-8');
}
ajaxRequest.send(parameters);
if (!asynchronous) ajaxBindCallback();
}
else alert("Unable to build XMLHttpRequest");
}
The script also supplies 2 helper methods easy retrieval of data from an XML document.
function getXMLEntries(xmlBranch, tagName)
{
var tagList = xmlBranch.getElementsByTagName(tagName);
var results = [];
var length = tagList.length;
for (var i=0; i < length; i++)
{
results.push(getXMLData(tagList[i]));
}
return results;
}
function getXMLData(xmlNode)
{
return xmlNode.firstChild ? xmlNode.firstChild.data : '';
}
Download the script
Download the script and have a play. It's completely free to use although a link referencing this page would be appreciated.
Comments
If you've got any questions or feedback about this article please post them in the Dynamic Tools Javascript Forum.