1. Home
  2. Computing & Technology
  3. JavaScript

Introduction to Ajax

4. Send the Request

clr gif
Join the Discussion

Questions? Comments?

Now that we have an event handler defined to test for when a resonse to our request is received we are now ready to send our request to the server. We do this by adding one extra line to our code.

ajaxObj.send(null);

This completes the code that we need to be able to create and send our request. The complete code that we have at this point looks like this:

function createXMLHttp() {
if (typeof XMLHttpRequest != 'undefined')
return new XMLHttpRequest();
else if (window.ActiveXObject) {
var avers = ["Microsoft.XmlHttp", "MSXML2.XmlHttp",
"MSXML2.XmlHttp.3.0", "MSXML2.XmlHttp.4.0",
"MSXML2.XmlHttp.5.0"];
for (var i = avers.length -1; i >= 0; i--) {
try {
httpObj = new ActiveXObject(avers[i]);
return httpObj;
} catch() {}
}
}
throw new Error('XMLHttp (AJAX) not supported');
}

var ajaxObj = createXMLHttp();
var url = 'myrequest.php';
ajaxObj.open("GET", url, true);
ajaxObj.onreadystatechange = function() {
ajaxObj.processRequest();}
ajaxObj.send(null);

ajaxObj.processRequest = function() {
if (this.readyState == 4) {
// got response
}
}
Explore JavaScript
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. JavaScript

©2009 About.com, a part of The New York Times Company.

All rights reserved.