Classic AJAX

AJAX stands for Asynchronous JavaScript And XML and has become an integral part of JavaScript coding. Implementing AJAX can often be simplified by using a JavaScript framework, like jQuery. Sometimes a framework is not available and you must use classic JavaScript. No need to worry, it is easily done using the code snippets below.


First define the Ajax HTTP request object.



function getHTTPObject()
{
var xmlhttp;
/*@cc_on
@if (@_jscript_version >= 5)
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
@else
xmlhttp = false;
@end @*/
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
}


An Ajax HTTP request can be made different ways, with GET and POST the most commonly used.


First create the Ajax request object and define a function to handle the response.

var ajax = getHTTPObject(); // See code snippet above
ajax.onreadystatechange=function()
{
/*
* Ready state:
* 0 = The request is not initialized
* 1 = The request has been set up
* 2 = The request has been sent
* 3 = The request is in process
* 4 = The request is complete
*/
if (ajax.readyState == 4) {
// Show response in alert box
alert('AJAX response = ' + ajax.responseText);
}
} // function

GET request:

// Open a connection to the server
/*
* param1 - Request method - GET or POST
* param2 - Server URL to send request
* param3 - Asynchronous connection (true for Ajax requests)
*/
ajax.open('GET', 'yoururl?yourparm1='+value1, true);
// Send the request
ajax.send(null);

POST request:

// Create a variable for the POST parameters
var params = 'parm1=value1&parm2=value2';
// Opening the server connection is the same, apart from the method parameter
ajax.open('POST', url, true);
//Send the proper header information along with the request
// Set the content type to text/html for pages without forms
// Pages with forms should have a content type of "application/x-www-form-urlencoded"
ajax.setRequestHeader("Content-type", "text/html");
ajax.setRequestHeader("Content-length", params.length);
ajax.setRequestHeader("Connection", "close");
// Send POST request
ajax.send(params);


If you need to access to the DOM (document object model) then use the responseXML property of the HTTP request object.
NOTE: The content type must be application/xml or text/xml for the responseXML property to be populated.



if (ajax.readyState == 4) {
// Show XML response in alert box
alert('AJAX response = ' + ajax.responseXML);
// Show "location" element value in alert box
alert(ajax.responseXML.documentElement.
getElementsByTagName("location")[0].firstChild.data);
}






This entry was posted in JavaScript and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *


*