AJAX: The XMLHttpRequest Object

*Creating Object
For Safari and Mozilla, a simple call to the object's constructor function does the job:
var req = new XMLHttpRequest();
For IE or other browsers use ActiveX, pass the name of the object to the ActiveX constuctor:
var req = new ActiveXObject("Microsoft.XMLHttp");
* Object methods:
The methods supported by Safari 1.2, Mozilla, and IE5 or later:

  • abort(): Stops the current request
  • getAllResponseHeaders(): Returns complete set of headers (labels and values) as a string.
  • getResponseHeader("headerLabel"): Returns the string value of a single header label.
  • open("method", "URL"[, asyncFlag[, "userName"[, "password"]]]): Assigns destination URL, method, and other optional attributes of a pending request.
  • send(content): Transmits the request, optionally with postable string or DOM object data.
  • setRequestHeader("label", "value"): Assigns a label/value pair to the header to be sent with a request.


var req;

function loadAjax(url) {
req = false;
if(window.XMLHttpRequest && !(window.ActiveXObject)) {
try {
req = new XMLHttpRequest();
} catch(e) {
req = false;
}
} else if(window.ActiveXObject) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
req = false;
}
}
}
if(req) {
req.onreadystatechange = processAjaxFuntion;
req.open("GET", url, true);
req.send("");
}
}


* Object properties
All properties are read-only.
  • onreadystatechange: Event handler for an event that fires at every state change.
  • readyState: Object status integer:
0 = uninitialized
1 = loading
2 = loaded
3 = interactive
4 = complete

  • responseText: String version of data returned from server process.
  • responseXML: DOM-compatible document object of data returned from server process.
  • status: Numeric code returned by server, such as 404 for "Not Found" or 200 for "OK".
  • statusText: String message accompanying the status code.


function processAjaxFuntion() {
// only if req shows "loaded"
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
// ...processing statements go here...
} else {
alert("There was a problem retrieving the data:\n" +
req.statusText);
}
}
}

Comments