Short Ajax Script
I wanted to see how small you could make a fully functional AJAX script that worked cross-browser and degraded gracefully, so I went through an old custom AJAX script and made it as small as I possibly could. In the resulting AJAX scripts, the post version is 410 characters and the GET version is only 359 characters long. The scripts are fully functional and accept the following parameters: URL, DATA (in string form), and ELEMENT (to update).
The scripts could be a little smaller, but it would really kill readability.
“Get” AJAX Script
function a(l,d,u){
try{r = new XMLHttpRequest();}catch(e){try {r = new ActiveXObject('Msxml2.XMLHTTP');}catch(e){r = new ActiveXObject('Microsoft.XMLHTTP');}}
if(r){
r.onreadystatechange = function() {if (r.readyState == 4 && r.status == 200){document.getElementById(u).innerHTML = r.responseText;}}
r.open('GET', l+'?'+d, true);r.send(d);
}
}
“Post” AJAX Script
function b(l,d,u){
try{r = new XMLHttpRequest();} catch(e){try {r = new ActiveXObject('Msxml2.XMLHTTP');} catch(e){r = new ActiveXObject('Microsoft.XMLHTTP');}}
if(r){
r.onreadystatechange = function() {if (r.readyState == 4 && r.status == 200){document.getElementById(u).innerHTML=r.responseText;}}
r.open('POST', l, true);r.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');r.send(d);
}
}
Combined AJAX Script
This combined script also accepts a fourth parameter ‘p’ that should evaluate true if the data is to be sent by post.
function a(l,d,u,p){
try{r = new XMLHttpRequest();}catch(e){try {r = new ActiveXObject('Msxml2.XMLHTTP');}catch(e){r = new ActiveXObject('Microsoft.XMLHTTP');}}
if(r){
r.onreadystatechange = function() {if (r.readyState == 4 && r.status == 200){document.getElementById(u).innerHTML = r.responseText;}}
if(p){r.open('POST', l, true);r.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');}else{r.open('GET', l+'?'+d, true);}
}
}
Demo: (Sorry but you will have to go to the full page so the JavaScript is loaded.)
Click here to see the POST HTML of the homepage
Click here to see the GET HTML of the homepage
(they are the same)