I hate the term “ajax” and I mostly refuse to use it… So I will refrain here.
The following javascript provides the basic/core functionality for all modern web applications: the asynchronous HTTP request.
function doHttpRequest( strUrl, objRequestData, bDoPost, callback ) { var xmlhttp = new XMLHttpRequest(); if(!xmlhttp) { alert('Your browser is too old... Sorry.'); } else { var strRequestData = ""; for( var strKey in objRequestData ) { var strValue = objRequestData[strKey]; if( strRequestData.length>0 ) { strRequest += "&"; } strRequestData += encodeURIComponent(strKey) + "=" + encodeURIComponent(strValue); } xmlhttp.onreadystatechange = function() { if(xmlhttp.readyState == 4) { if( xmlhttp.status!=200 ) { alert("Error in HTTP Request...\n\nStatus: "+xmlhttp.status+"\n"+xmlhttp.statusText); } else { var cbParams = { 'xmlhttp':xmlhttp }; callback(cbParams); } } } if( bDoPost ) { xmlhttp.open("POST", strUrl, true); xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlhttp.send(strRequestData); } else { xmlhttp.open("GET", strUrl+"?"+strRequestData, true); xmlhttp.send(null); } } }
Anyway, that’s all mostly for my benefit. I usually end up having to write that stupid function from scratch once or twice a month…
You also may ask “why would you bother with the nuts-and-bolts like this when you could use some existing javascript library/framework?”. Well, there are people who use frameworks … and then there are the people who write the frameworks. There’s a lot more job security in the latter :)