Basic Ajax Syntax





27
Date Submitted Thu. Oct. 5th, 2006 8:12 PM
Revision 1 of 1
Helper Thomas
Tags ajax | JavaScript
Comments 3 comments
The basic framework of an Ajax-enabled web page. The following JavaScript shows how to send a request for an XML file and how to receive that request. Of course, in a real life scenario, you'll have to implement better error trapping and actually do something with the XML that gets returned.

/* -- Function to "handle" the response -- */
function myHandler() {
  /* -- Was the request successful? -- */
  if (this.readyState == 4 && this.status == 200) {
    /* -- Did the request return a result? -- */
    if (this.responseXML != null && this.responseXML.getElementById("stuff").firstChild.data) {
      doSomething(this.responseXML.getElementById("stuff").firstChild.data);
    }
  }
}

var myRequest; // Variable to hold request object

if (window.XMLHttpRequest) {
  myRequest = new XMLHttpRequest(); // Standards-compliant browsers
} else if (window.ActiveXObject) {
  myRequest = new ActiveXObject("Msxml2.XMLHTTP"); // For IE
}

myRequest.onreadystatechange = myHandler;
/* -- "getStuff.php" can be anything that returns an XML file -- */
myRequest.open("GET", "getStuff.php", true);

Thomas Higginbotham

thomashigginbotham.com/

Comments

Comments Modification as class
Thu. Oct. 5th, 2006 10:14 PM    Scripter Fordiman
  Comments Status code?
Sun. Oct. 8th, 2006 2:51 AM    Helper mceppi
  Comments Thanks
Fri. Oct. 6th, 2006 6:58 AM    Helper Thomas

Voting