Ajax : Origins

AJAX is another one of those fancy acronyms depicting a set of technologies ( HTML, JavaScript, CSS ) enabling more robust client-side (i.e. in the browser) type of development.

Source: Wikipedia

Ajax (also AJAX; pronounced /ˈeɪdʒæks/; an acronym for asynchronous JavaScript and XML)[1] is a group of interrelated web development methods used on the client-side to create interactive web applications. With Ajax, web applications can send data to, and retrieve data from, a server asynchronously (in the background) without interfering with the display and behavior of the existing page. Data is usually retrieved using the XMLHttpRequest object. Despite the name, the use of XML is not needed (JSON is often used instead), and the requests don’t need to be asynchronous. 

The heart of Ajax is the XMLHttpRequest  API which allows the retrieval of data from a server, most likely in an asynchronous manner.  Of course different browsers have different implementations of this API, thus one must be cognizant of such idiosyncrasies.  

Let’s have a look at a simple code example in order to demonstrate Ajax in action.  Please see the previous link to see all possible statuses for XMLHttpRequest.  This simple sample just invokes an HTTP GET request against a Twitter API, which on success just returns the string “ok”.


function testTwitterApi()
{
var xmlhttp;
if (window.XMLHttpRequest){
  //IE7+ and other major browsers
  xmlhttp=new XMLHttpRequest();
}
else{
// pre IE7 
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("response").innerHTML=xmlhttp.responseText;
    }
  }
  
xmlhttp.open("GET","http://api.twitter.com/1/help/test.json",true);
xmlhttp.send();
}

And here is the html:

<div id="response"></div>
<button type="button" onclick="testTwitterApi()">Test Twitter API</button>

In the next blog post we’ll get out of the past and work smarter using the widely adopted JQuery Javascript library to take care of our Ajax needs.

In saying that, I think it is always good to learn the origins/foundations of a technology for a deeper understanding of what is going on under the covers, especially when troubleshooting incurs.

Syntax highlighting in Tumblr

How to add code syntax to your blog posts in Tumblr.  Please share alternatives that you know of.