Loading

Tuesday, December 25, 2007

AJAX at work - Sample program demonstrating AJAX

//Select this following code, paste in dreamweaver or any text editor.
// save them in any web server root directory. I saved in wwwroot of
// Inetpub. execute the program using "http" protocol for instance //"http://localhost/ajaxprograms/Index.html" .

//Index.html


<html>

<head>
<title> Ajax at work <⁄title>

<script language = "javascript">
var XMLHttpRequestObject = false;

if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}

function getData(dataSource, divID)
{
if(XMLHttpRequestObject) {
var obj = document.getElementById(divID);
XMLHttpRequestObject.open("GET", dataSource);

XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 4 &&
XMLHttpRequestObject.status == 200) {
obj.innerHTML = XMLHttpRequestObject.responseText;
}
}

XMLHttpRequestObject.send(null);
}
}
<⁄script>
<⁄head>

<body>

<h1> Fetching data with Ajax <⁄h1>

<form<
<input type = "button" value = "Display Message"
onclick = "getData('data.txt', 'targetDiv')">
<⁄form>

<div id="targetDiv">
<p>The fetched data will go here.<⁄p>
<⁄div>

<⁄body>
<⁄html>

//data.txt
This text was fetched using Ajax.

Let us revise some key points about AJAX step by step:

The XMLHttpRequest object is the heart and soul of Ajax. Its methods and properties drive the asynchronous requests that make Ajax applications feel so responsive.

In this sample AJAX program, we’ve seen how to use the XMLHttpRequest object in three steps:

1. Create an instance of the object that will work across different browser implementations.
2. Prepare a request using the onreadystatechange event handler, the open method, and the send method.
3. Process the response from the server through the properties readyState, status, responseText, and sometimes responseXML.

This basic model will remain unchanged for all the AJAX programs.


SHARE TWEET

Thank you for reading this article AJAX at work - Sample program demonstrating AJAX With URL http://x-tutorials.blogspot.com/2007/12/ajax-at-work-sample-program.html. Also a time to read the other articles.

0 comments:

Write your comment for this article AJAX at work - Sample program demonstrating AJAX above!