Sunday, January 4, 2009

A First AJAX Program

This post should be able to answer the following questions:
  1. How to create the simplest AJAX program?
  2. I need a simple AJAX template from where I can begin coding.
The code sample given below has been executed on Mozilla Firefox version 3.0.5 and uses Apache Tomcat 6.0 as the application server.

I make use of 2 files. Ajax1.html and data.txt. Both these files have been placed in a folder named 'myajax' in the 'webapps' directory of tomcat.

My first file is a simple html file that contains a small amount of javascript that does the magic trick for us. The second file contains the a few lines of text that is magically transferred using AJAX.


-------------------Start Of Sample Code--------------------
Ajax1.html

<html>
<head>
<script language="javascript">

var ajaxObj=false;

if(window.XMLHttpRequest)
{
ajaxObj=new XMLHttpRequest();
}

function magicByAjax()
{
var obj=document.getElementById('target1');
if(ajaxObj)
{
ajaxObj.open("GET","http://localhost:8080/myajax/data.txt",true);
ajaxObj.onreadystatechange=function()
{
if(ajaxObj.readyState==4&&ajaxObj.status==200)
{
obj.innerHTML=ajaxObj.responseText;
}
}
ajaxObj.send(null);
}
}

</script>

</head>
<body>
<input type="button" value="Click Me To See Some Ajax Magic" onclick="magicByAjax()" id="b1"/>
<br/>
<div id='target1'>
Data fetched from server goes here
</div>
</body>
</html>


data.txtWush! Bang! Here I come from server-land.

----------------------End of sample code-------------------------

Start the tomcat server.
Type the following url in Mozilla Firefox:

http://localhost:8080/myajax/Ajax1.html

Click on the button and enjoy the magic.

Happy Programming ;)

Signing Off
Ryan

No comments: