Andy’s Blog: Application Express etc.


Ajax: Hello World

Posted in Ajax by Andrew Tulley on March 24, 2007

AjaxThere are lots of pre-built javascript functions you can get your hands on which offer Ajax functionality (such as ApEx’s htmldb_Get() function). On the one hand, these are great for productivity because they remove much of the complexity of writing Ajaxified javascript. On the other, they can make it very difficult to understand the basic underlying concepts: “What actually happens with all this Ajax stuff?”

Initially, to get a handle on what Ajax “does” and how, in code, it does it, I found it very useful to write the most basic function I could, working on the principle that one good example is as good as a hundred lines of explanation. So here it is, an Ajaxified “Hello World”.

You can see it in action here: http://andrew.tulley.co.uk/blogfiles/ajax_hello_world.html

And the code:

<html>
<head>
<script>
function getXmlHttpRequestObject() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest(); //Not IE
} else if(window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP"); //IE
} else {
alert("Your browser can't handle AJAX type stuff. Better upgrade to F1r3foks.");
}
}

function sayHello() {
if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {
receiveReq.open('GET','hello_world.txt',true);
receiveReq.onreadystatechange = handleSayHello;
receiveReq.send(null);
}
}

function handleSayHello() {
if (receiveReq.readyState == 4) {
document.getElementById('receiveDiv').innerHTML = receiveReq.responseText;
}
}

var receiveReq = getXmlHttpRequestObject();
</script>
</head>

<body>
<h3>Ajax Hello World</h3>
<div>
<a href=”javascript:sayHello();”>[ Hello World! ]</a>
</div>

<div name=”receiveDiv” id=”receiveDiv” class=”textDiv1″>
</div>
</body>
</html>

Leave a Reply