Appendix . Ajax For Dummies®

Ajax For Dummies®
Ajax For Dummies®

Configuring an XMLHttpRequest object

To configure an XMLHttpRequest object in JavaScript for use with a particular URL:

XMLHttpRequestObject.open("GET";, url);

Fetching your data

To make the browser fetch data from the URL you’ve configured the XMLHttpRequest object for, use this JavaScript:

XMLHttpRequestObject.send(null);

Creating an XMLHttpRequest object

To create an XMLHttpRequest object in JavaScript:

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

Setting up the callback function

To create a function that will be called back when your data has been fetched:

XMLHttpRequestObject.onreadystatechange = function()
{
  if (XMLHttpRequestObject.readyState == 4 &&
    XMLHttpRequestObject.status == 200) {
      //Handle XMLHttpRequestObject.responseText or
      //Handle XMLHttpRequestObject.responseXML here.
  }
}

Important XMLHttpRequest object properties

onreadystatechange: Contains the name of the event handler that should be called when the value of the readyState property changes. Read/write.

readyState: Contains the current state of the request. Read-only.

responseText: Contains the downloaded data as a string. Read-only.

Get Ajax For Dummies® now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.