If you want to have an AJAX application, this simple code is what you must have first.
var xml = make_xml();Save the code in "ajax.js" and call it in your HTML <head> section like this:
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();
}
}
<script language="javascript" type="text/javascript"Next, you need to have a handle to handle submitted forms like this:
src="ajax.js"></script>
function handle_submit () {In order to save time, I prefer to replace the long "document.getElementById" with a simple get() function, like this:
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;
}
function get (id) {Next, you need to have a handle to load onsubmit action, like this:
return document.getElementById(id);
}
function load_handler () {Don't forget to call the handle during page load, like this:
get('action1').onsubmit = handle_submit;
}
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!