Saturday, March 14, 2009

Basic AJAX code

If you want to have an AJAX application, this simple code is what you must have first.

var xml = make_xml();
function make_xml () {
if (typeof XMLHttpRequest == 'undefined') {
objects = Array(
'Microsoft.XMLHTTP',
'MSXML2.XMLHTTP',
'MSXML2.XMLHTTP.3.0',
'MSXML2.XMLHTTP.4.0',
'MSXML2.XMLHTTP.5.0'
);
for (i in objects) {
try {
return new ActiveXObject(objects[i]);
} catch (e) {}
}
} else {
return new XMLHttpRequest();
}
}
Save the code in "ajax.js" and call it in your HTML <head> section like this:
<script language="javascript" type="text/javascript"
src="ajax.js"></script>
Next, you need to have a handle to handle submitted forms like this:
function handle_submit () {
xml.open('post', root + '/');
xml.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xml.onreadystatechange = function () {
if (xml.readyState == 4) {
data = xml.responseText.split ( "[BRK]" );
get('div1').innerHTML = data[0];
get('div2').innerHTML = data[1];
} else {
get('div1').innerHTML = 'Please wait';
get('div2').innerHTML = 'Please wait';
}
}
if (window.encodeURI(get('action').value) == 'action1') {
xml.send('action=' + window.encodeURI(get('action').value) + '&javascript=1&
field1=' + window.encodeURI(get('field1').value) + '&field2=' +
window.encodeURI(get('field2').value));
} else if (window.encodeURI(get('action').value) == 'action2') {
xml.send('action=' + window.encodeURI(get('action').value) + '&javascript=1');
}
return false;
}
In order to save time, I prefer to replace the long "document.getElementById" with a simple get() function, like this:
function get (id) {
return document.getElementById(id);
}
Next, you need to have a handle to load onsubmit action, like this:
function load_handler () {
get('action1').onsubmit = handle_submit;
}
Don't forget to call the handle during page load, like this:
window.onload = load_handler;

Using this basic AJAX code, you may do all the web interactivity using AJAX, easily.

All the other codes didn't change at all, including HTML forms, PHP codes, etc. All you have to do is just synchronize the ID's of your HTML forms with your "ajax.js" ID's, otherwise it won't recognize your request.

Any questions, please write on the comment form. Good luck!