Home > Ajax > Ajax: Hello World

Ajax: Hello World

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>

Advertisements
Categories: Ajax
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: