Helping ordinary people create extraordinary websites!
HOME TUTORIALS SCRIPTS WEB HOSTING BLOG FORUM
Get Our Newsletter
Email:

XMLHttpRequest Reference

XMLHttpRequest Reference Cheat Sheet

Now that we've covered the use of these objects, this cheatsheet will help you as your code your applications. Remember to bookmark this and refer back to it as you code your AJAX applications.

Quick start

function ajax_request(url, data, callback) {
try {
xhrobj = new XMLHttpRequest();
} catch (e) {
try {
xhrobj=new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xhrobj=new ActiveXObject("Microsoft.XMLHTTP");
}
}

xhrobj.open("GET", url);
xhrobj.setRequestHeader("X-Requested-With", "XMLHttpRequest");

xhrobj.onreadystatechange = function() {
if (xhrobj.readyState == 4 && xhrobj.status == 200) {
callback(xhrobj.responseText);
}
};
xhrobj.send(data);
}

Examples:

ajax_request("backend.php", null, function(data){ return });
ajax_request("backend.php", null, function(data){ alert(data); });
ajax_request("backend.php?var1=value&var2=value", null, function(data){ return });

You must specify a callback function. However, the callback function does not need to do anything and can simply return. If you need to send data in the message body (e.g. for some remote procedure calls), substitute the null in the second parameter with a string of data.

XMLHttpRequest Reference

Methods

abort()Cancel the current request.
getAllResponseHeaders()Get a string of the response headers.
getResponseHeader(header_name)Get the value of header header_name.
open(method, url)Create request to url using method. method can be "GET", "POST", "HEAD" etc.
setRequestHeader(name, value)Set header name to value.
send(data)Send the request with message body data.

Properties

readyStateProgress of the request; see callback function notes.
responseText Response of server as a string
responseXML If the response was an XML document, this will be a parsed XML node tree that can be manipulated just like the document.
onreadystatechangeCallback function for event fired at any state change.
statusHTTP status code of the response.
statusTextThe textual version of the status.
« Abstracting the XHR

More AJAX Tutorials:
» Getting Started with AJAX in jQuery
» Five Ways to Spice Up Your Site with jQuery
» AJAX Accessibility for Websites
» GWT Basics: AJAX Programming with Java
» A Designer's Guide to Prototyping Ajax
» AJAX and PHP Form Processing
Ask A Question
characters left.