Tuesday, August 28, 2007

Ajax Introduction for Ajax Beginers

Ajax
AJAX stands for Asynchronous JavaScript And XML.
AJAX is a type of programming made popular in 2005 by Google (with Google Suggest).
AJAX is not a new programming language, but a new way to use existing standards.
With AJAX you can create better, faster, and more user-friendly web applications.
AJAX is based on JavaScript and HTTP requests.

AJAX Introduction
________________________________________
What You Should Already Know
Before you continue you should have a basic understanding of the following:
• HTML / XHTML
• JavaScript
AJAX = Asynchronous JavaScript and XML
AJAX is not a new programming language, but a technique for creating better, faster, and more interactive web applications.
With AJAX, your JavaScript can communicate directly with the server, using the JavaScript XMLHttpRequest object. With this object, your JavaScript can trade data with a web server, without reloading the page.
AJAX uses asynchronous data transfer (HTTP requests) between the browser and the web server, allowing web pages to request small bits of information from the server instead of whole pages.
The AJAX technique makes Internet applications smaller, faster and more user-friendly.
AJAX is a browser technology independent of web server software.

AJAX is Based on Web Standards
AJAX is based on the following web standards:
• JavaScript
• XML
• HTML
• CSS
The web standards used in AJAX are well defined, and supported by all major browsers. AJAX applications are browser and platform independent.
AJAX is About Better Internet Applications
Web applications have many benefits over desktop applications; they can reach a larger audience, they are easier to install and support, and easier to develop.
However, Internet applications are not always as "rich" and user-friendly as traditional desktop applications.
With AJAX, Internet applications can be made richer and more user-friendly.
AJAX Uses HTTP Requests
In traditional JavaScript coding, if you want to get any information from a database or a file on the server, or send user information to a server, you will have to make an HTML form and GET or POST data to the server. The user will have to click the "Submit" button to send/get the information, wait for the server to respond, then a new page will load with the results.
Because the server returns a new page each time the user submits input, traditional web applications can run slowly and tend to be less user-friendly.
With AJAX, your JavaScript communicates directly with the server, through the JavaScript XMLHttpRequest object
With an HTTP request, a web page can make a request to, and get a response from a web server - without reloading the page. The user will stay on the same page, and he or she will not notice that scripts request pages, or send data to a server in the background.
The XMLHttpRequest Object
By using the XMLHttpRequest object, a web developer can update a page with data from the server after the page has loaded!
AJAX was made popular in 2005 by Google (with Google Suggest).
Google Suggest is using the XMLHttpRequest object to create a very dynamic web interface: When you start typing in Google's search box, a JavaScript sends the letters off to a server and the server returns a list of suggestions.
The XMLHttpRequest object is supported in Internet Explorer 5.0+, Safari 1.2, Mozilla 1.0 / Firefox, Opera 8+, and Netscape 7.
Your First AJAX Application
To understand how AJAX works, we will create a small AJAX application.
First, we are going to create a standard HTML form with two text fields: username and time. The username field will be filled in by the user and the time field will be filled in using AJAX.
The HTML file will be named "testAjax.htm", and it looks like this (notice that the HTML form below has no submit button!):



Name:
Time:




AJAX - Browser Support
The keystone of AJAX is the XMLHttpRequest object.
Different browsers use different methods to create the XMLHttpRequest object.
Internet Explorer uses an ActiveXObject, while other browsers uses the built-in JavaScript object called XMLHttpRequest.
To create this object, and deal with different browsers, we are going to use a "try and catch" statement. You can read more about the try and catch statement in our JavaScript tutorial.
Let's update our "testAjax.htm" file with the JavaScript that creates the XMLHttpRequest object:




Name:
Time:



Example explained: First create a variable xmlHttp to hold the XMLHttpRequest object.
Then try to create the object with XMLHttp=new XMLHttpRequest(). This is for the Firefox, Opera, and Safari browsers. If that fails, try xmlHttp=new ActiveXObject("Msxml2.XMLHTTP") which is for Internet Explorer 6.0+, if that also fails, try xmlHttp=new ActiveXObject("Microsoft.XMLHTTP") which is for Internet Explorer 5.5+
If none of the three methods work, the user has a very outdated browser, and he or she will get an alert stating that the browser doesn't support AJAX.
Note: The browser-specific code above is long and quite complex. However, this is the code you can use every time you need to create an XMLHttpRequest object, so you can just copy and paste it whenever you need it. The code above is compatible with all the popular browsers: Internet Explorer, Opera, Firefox, and Safari.
AJAX - More About the XMLHttpRequest Object
Before sending data to the server, we have to explain three important properties of the XMLHttpRequest object.
The onreadystatechange Property
After a request to the server, we need a function that can receive the data that is returned by the server.
The onreadystatechange property stores the function that will process the response from a server. The following code defines an empty function and sets the onreadystatechange property at the same time:
xmlHttp.onreadystatechange=function()
{
// We are going to write some code here
}

The readyState Property
The readyState property holds the status of the server's response. Each time the readyState changes, the onreadystatechange function will be executed.
Here are the possible values for the readyState property:
State Description
0 The request is not initialized
1 The request has been set up
2 The request has been sent
3 The request is in process
4 The request is complete

We are going to add an If statement to the onreadystatechange function to test if our response is complete (this means that we can get our data):

xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
// Get the data from the server's response
}
}
The responseText Property
The data sent back from the server can be retrieved with the responseText property.
In our code, we will set the value of our "time" input field equal to responseText:
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
document.myForm.time.value=xmlHttp.responseText;
}
}
AJAX - Sending a Request to the Server
To send off a request to the server, we use the open() method and the send() method.
The open() method takes three arguments. The first argument defines which method to use when sending the request (GET or POST). The second argument specifies the URL of the server-side script. The third argument specifies that the request should be handled asynchronously. The send() method sends the request off to the server. If we assume that the HTML and ASP file are in the same directory, the code would be:
xmlHttp.open("GET","time.asp",true);
xmlHttp.send(null);
Now we must decide when the AJAX function should be executed. We will let the function run "behind the scenes" when the user types something in the username text field:

Name: onkeyup="ajaxFunction();" name="username" />
Time:

Our updated AJAX-ready "testAjax.htm" file now looks like this:




Name: onkeyup="ajaxFunction();" name="username" />
Time:



AJAX - The Server-Side ASP Script
Now we are going to create the script that displays the current server time.
The responseText property (explained in the previous chapter) will store the data returned from the server. Here we want to send back the current time. The code in "time.asp" looks like this:
<%
response.expires=-1
response.write(time)
%>
Run Your AJAX Application
Try the AJAX application by typing some text into the Name text box below, then click inside the Time text box:
Name: Time:
The Time text box gets the server's time from "time.asp" file without reloading the page!
We have seen that AJAX can be used to create more interactive applications.
AJAX Suggest Example
In the AJAX example below we will demonstrate how a web page can communicate with a web server online as a user enters data into a standard HTML form.
________________________________________
Type a Name in the Box Below
First Name:
Suggestions:
Example Explained - The HTML Form
The form above has the following HTML code:

First Name:
onkeyup="showHint(this.value)">

Suggestions:


As you can see it is just a simple HTML form with an input field called "txt1".
An event attribute for the input field defines a function to be triggered by the onkeyup event.
The paragraph below the form contains a span called "txtHint". The span is used as a placeholder for data retrieved from the web server.
When the user inputs data, a function called "showHint()" is executed. The execution of the function is triggered by the "onkeyup" event. In other words: Each time the user moves his finger away from a keyboard key inside the input field, the function showHint is called.
Example Explained - The showHint() Function
The showHint() function is a very simple JavaScript function placed in the section of the HTML page.
The function contains the following code:
function showHint(str)
{
if (str.length==0)
{
document.getElementById("txtHint").innerHTML="";
return;
}
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
var url="gethint.asp";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
The function executes every time a character is entered in the input field.
If there is some input in the text field (str.length > 0) the function executes the following:
• Defines the url (filename) to send to the server
• Adds a parameter (q) to the url with the content of the input field
• Adds a random number to prevent the server from using a cached file
• Creates an XMLHTTP object, and tells the object to execute a function called stateChanged when a change is triggered
• Opens the XMLHTTP object with the given url.
• Sends an HTTP request to the server
If the input field is empty, the function simply clears the content of the txtHint placeholder.
Example Explained - The GetXmlHttpObject() Function
The example above calls a function called GetXmlHttpObject().
The purpose of the function is to solve the problem of creating different XMLHTTP objects for different browsers.
The function is listed below:
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
Example Explained - The stateChanged() Function
The stateChanged() function contains the following code:
function stateChanged()
{
if (xmlHttp.readyState==4)
{
document.getElementById("txtHint").innerHTML=xmlHttp.responseText;
}
}
The stateChanged() function executes every time the state of the XMLHTTP object changes.
When the state changes to 4 ("complete"), the content of the txtHint placeholder is filled with the response text.
AJAX Source Code to Suggest Example
The source code below belongs to the AJAX example on the previous page.
You can copy and paste it, and try it yourself.
The AJAX HTML Page
This is the HTML page. It contains a simple HTML form and a link to a JavaScript.






First Name:
onkeyup="showHint(this.value)">

Suggestions:




The AJAX JavaScript
This is the JavaScript code, stored in the file "clienthint.js":
var xmlHttp

function showHint(str)
{
if (str.length==0)
{
document.getElementById("txtHint").innerHTML="";
return;
}
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
var url="gethint.asp";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}

function stateChanged()
{
if (xmlHttp.readyState==4)
{
document.getElementById("txtHint").innerHTML=xmlHttp.responseText;
}
}

function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
The AJAX Server Page - ASP and PHP
There is no such thing as an AJAX server. AJAX pages can be served by any internet server.
The server page called by the JavaScript in the example from the previous chapter is a simple ASP file called "gethint.asp".
Below we have listed two examples of the server page code, one written in ASP and one in PHP.
AJAX ASP Example
The code in the "gethint.asp" page is written in VBScript for an Internet Information Server (IIS). It just checks an array of names and returns the corresponding names to the client:
<%
response.expires=-1
dim a(30)
'Fill up array with names
a(1)="Anna"
a(2)="Brittany"
a(3)="Cinderella"
a(4)="Diana"
a(5)="Eva"
a(6)="Fiona"
a(7)="Gunda"
a(8)="Hege"
a(9)="Inga"
a(10)="Johanna"
a(11)="Kitty"
a(12)="Linda"
a(13)="Nina"
a(14)="Ophelia"
a(15)="Petunia"
a(16)="Amanda"
a(17)="Raquel"
a(18)="Cindy"
a(19)="Doris"
a(20)="Eve"
a(21)="Evita"
a(22)="Sunniva"
a(23)="Tove"
a(24)="Unni"
a(25)="Violet"
a(26)="Liza"
a(27)="Elizabeth"
a(28)="Ellen"
a(29)="Wenche"
a(30)="Vicky"
'get the q parameter from URL
q=ucase(request.querystring("q"))
'lookup all hints from array if length of q>0
if len(q)>0 then
hint=""
for i=1 to 30
if q=ucase(mid(a(i),1,len(q))) then
if hint="" then
hint=a(i)
else
hint=hint & " , " & a(i)
end if
end if
next
end if
'Output "no suggestion" if no hint were found
'or output the correct values
if hint="" then
response.write("no suggestion")
else
response.write(hint)
end if
%>
AJAX PHP Example
The code above rewritten in PHP.
Note: To run the entire example in PHP, remember to change the value of the url variable in "clienthint.js" from "gethint.asp" to "gethint.php".
AJAX Database Example
In the AJAX example below we will demonstrate how a web page can fetch information from a database using AJAX technology.
________________________________________
Select a Name in the Box Below
Select a Customer:
Customer info will be listed here.
AJAX can be used for interactive communication with a database.
AJAX Example Explained
The example above contains a simple HTML form and a link to a JavaScript:






Select a Customer:



Customer info will be listed here.




As you can see it is just a simple HTML form with a drop down box called "customers".
The paragraph below the form contains a div called "txtHint". The div is used as a placeholder for info retrieved from the web server.
When the user selects data, a function called "showCustomer()" is executed. The execution of the function is triggered by the "onchange" event. In other words: Each time the user change the value in the drop down box, the function showCustomer is called.
The JavaScript code is listed below.
The AJAX JavaScript
This is the JavaScript code stored in the file "selectcustomer.js":
var xmlHttp

function showCustomer(str)
{
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
var url="getcustomer.asp";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}

function stateChanged()
{
if (xmlHttp.readyState==4)
{
document.getElementById("txtHint").innerHTML=xmlHttp.responseText;
}
}

function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
The AJAX Server Page
The server page called by the JavaScript, is a simple ASP file called "getcustomer.asp".
The page is written in VBScript for an Internet Information Server (IIS). It could easily be rewritten in PHP, or some other server language. Look at a corresponding example in PHP.
The code runs an SQL against a database and returns the result as an HTML table:
<%
response.expires=-1
sql="SELECT * FROM CUSTOMERS WHERE CUSTOMERID="
sql=sql & "'" & request.querystring("q") & "'"

set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open(Server.Mappath("/db/northwind.mdb"))
set rs = Server.CreateObject("ADODB.recordset")
rs.Open sql, conn

response.write("")
do until rs.EOF
for each x in rs.Fields
response.write("")
response.write("")
next
rs.MoveNext
loop

response.write("
" & x.name & "" & x.value & "
")
%>
AJAX can be used for interactive communication with an XML file.
AJAX XML Example
In the AJAX example below we will demonstrate how a web page can fetch information from an XML file using AJAX technology.
Select a CD in the Box Below
Select a CD:
CD info will be listed here.
AJAX Example Explained
The example above contains a simple HTML form and a link to a JavaScript:






Select a CD:



CD info will be listed here.




As you can see it is just a simple HTML form with a simple drop down box called "cds".
The paragraph below the form contains a div called "txtHint". The div is used as a placeholder for info retrieved from the web server.
When the user selects data, a function called "showCD" is executed. The execution of the function is triggered by the "onchange" event. In other words: Each time the user change the value in the drop down box, the function showCD is called.
The JavaScript code is listed below.
The AJAX JavaScript
This is the JavaScript code stored in the file "selectcd.js":
var xmlHttp
function showCD(str)
{
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
var url="getcd.asp";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
function stateChanged()
{
if (xmlHttp.readyState==4)
{
document.getElementById("txtHint").innerHTML=xmlHttp.responseText;
}
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
var xmlHttp
function showCD(str)
{
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
var url="getcd.asp";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
function stateChanged()
{
if (xmlHttp.readyState==4)
{
document.getElementById("txtHint").innerHTML=xmlHttp.responseText;
}
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
<%
response.expires=-1
q=request.querystring("q")

set xmlDoc=Server.CreateObject("Microsoft.XMLDOM")
xmlDoc.async="false"
xmlDoc.load(Server.MapPath("cd_catalog.xml"))

set nodes=xmlDoc.selectNodes("CATALOG/CD[ARTIST='" & q & "']")

for each x in nodes
for each y in x.childnodes
response.write("" & y.nodename & ": ")
response.write(y.text)
response.write("
")
next
next
%>

While responseText returns the HTTP response as a string, responseXML returns the response as XML.
The ResponseXML property returns an XML document object, which can be examined and parsed using W3C DOM node tree methods and properties.
AJAX ResponseXML Example
In the following AJAX example we will demonstrate how a web page can fetch information from a database using AJAX technology. The selected data from the database will this time be converted to an XML document, and then we will use the DOM to extract the values to be displayed.
________________________________________
Select a Name in the Box Below
Select a Customer:
AJAX Example Explained
The example above contains an HTML form, several elements to hold the returned data, and a link to a JavaScript:






Select a Customer:












The example above contains an HTML form with a drop down box called "customers".
When the user selects a customer in the dropdown box, a function called "showCustomer()" is executed. The execution of the function is triggered by the "onchange" event. In other words: Each time the user change the value in the drop down box, the function showCustomer() is called.
The JavaScript code is listed below.
The AJAX JavaScript
This is the JavaScript code stored in the file "selectcustomer_xml.js":
var xmlHttp
function showCustomer(str)
{
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
var url="getcustomer_xml.asp";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
function stateChanged()
{
if (xmlHttp.readyState==4)
{
var xmlDoc=xmlHttp.responseXML.documentElement;
document.getElementById("companyname").innerHTML=
xmlDoc.getElementsByTagName("compname")[0].childNodes[0].nodeValue;
document.getElementById("contactname").innerHTML=
xmlDoc.getElementsByTagName("contname")[0].childNodes[0].nodeValue;
document.getElementById("address").innerHTML=
xmlDoc.getElementsByTagName("address")[0].childNodes[0].nodeValue;
document.getElementById("city").innerHTML=
xmlDoc.getElementsByTagName("city")[0].childNodes[0].nodeValue;
document.getElementById("country").innerHTML=
xmlDoc.getElementsByTagName("country")[0].childNodes[0].nodeValue;
}
}

function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
The showCustomer() and GetXmlHttpObject() functions above are the same as in previous chapters. The stateChanged() function is also used earlier in this tutorial, however; this time we return the result as an XML document (with responseXML) and uses the DOM to extract the values we want to be displayed.
The AJAX Server Page
The server page called by the JavaScript, is a simple ASP file called "getcustomer_xml.asp".
The page is written in VBScript for an Internet Information Server (IIS). It could easily be rewritten in PHP, or some other server language. Look at a corresponding example in PHP.
The code runs an SQL query against a database and returns the result as an XML document:
<%
response.expires=-1
response.contenttype="text/xml"
sql="SELECT * FROM CUSTOMERS "
sql=sql & " WHERE CUSTOMERID='" & request.querystring("q") & "'"

on error resume next
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open(Server.Mappath("/db/northwind.mdb"))
set rs=Server.CreateObject("ADODB.recordset")
rs.Open sql, conn
if err <> 0 then
response.write(err.description)
set rs=nothing
set conn=nothing
else
response.write("")
response.write("")
response.write("" &rs.fields("companyname")& "")
response.write("" &rs.fields("contactname")& "")
response.write("
" &rs.fields("address")& "
")
response.write("" &rs.fields("city")& "")
response.write("" &rs.fields("country")& "")
response.write("
")
end if
on error goto 0
%>
Notice the second line in the ASP code above: response.contenttype="text/xml". The ContentType property sets the HTTP content type for the response object. The default value for this property is "text/html". This time we want the content type to be XML.
Then we select data from the database, and builds an XML document with the data
AppML is an open source initiative from W3Schools.
AppML uses AJAX technology.
What is AppML?
• AppML stands for Application Markup Language
• AppML uses XML to describe Internet applications
• AppML applications are self-describing
• AppML is a declarative language
• AppML is platform independent
• AppML uses AJAX technology
• AppML is an open source initiative from W3Schools
AppML is a Declarative Language
AppML is not a programming language. It is a declarative language, used to describe applications.
With AppML you can create Internet applications without programming.
Traditional applications are written in a programming language and compiled, with predefined data structures and functions. AppML allows the programmer to redefine both data and functions while the application is running.
Since AppML applications are written in XML, AppML applications are self-describing
AppML is Browser Independent
Since AppML only uses internet standards like HTML (XHTML), CSS, XML, and JavaScript, AppML will run in all browsers.
AppML Uses AJAX Technology
AppML uses AJAX technology. Internet communication between the web client and the web server is done with HTTP requests.
History
In 1999, the staff at W3Schools began developing AppML.
In September 2000, a development project for a large Norwegian customer was started. The goal of the project was to convert a huge information system from a Windows desktop application to a modern Internet application using only AppML.
The new AppML-based system was launched in 2001, several months before schedule, and it was one of the first commercial available AJAX applications.
The project was a huge success, with development time reduced by 75% compared to ordinary web development.
Since then, hundreds of new applications have been added, and AppML now covers over 1000 running applications.
In December 2006, W3Schools decided to offer AppML to the public, as an open source product, free of charge.
An Ajax “Hello World” project to get you going
A lead to a great posting Rasmus' 30 second Ajax tutorial was too good a treat not to share around. Sometimes we all want something very simple to build a thorough understanding of the mechanics of a new technique before we dive into the deeper water beyond. Now, if you are into ASP.NET and not PHP you might like to take a look at my version of this ultra-simple introduction to Ajax with sincere thanks to the original author. Now most simple introductions to Ajax using ASP.NET seem to quickly become complex - introducing libraries and DLLs and helper functions just about as soon as the first paragraph is over. This is because they all seem to miss out the fact that you have to work around the ASP.Net functionality to get thing working in a nice simple manner. I will try and take you through the steps that explain the problem and thus make the solutions seem much more obvious.

So let's get going. Create a new Web project and, to keep things very simple at this initial stage, add a couple of HTML controls - a text field and a button to the initial page. Note, not regular ASP.NET web forms controls - click the HTML tab.

Then add a JavaScript file to the project and paste the following into it:

function createRequestObject() {
var ro;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
ro = new ActiveXObject("Microsoft.XMLHTTP");
}else{
ro = new XMLHttpRequest();
}
return ro;
}

var http = createRequestObject();

function sndReq(action) {
http.open('POST', 'WebForm2.aspx?action='+action);
http.onreadystatechange = handleResponse;
http.send(null);
}

function handleResponse() {
if(http.readyState == 4){
var response = http.responseText;
alert(response);
document.getElementById('MessBox').value = response;
}
}

You will need to add a reference to this JavaScript file to the web page - although you could just add the script to that page directly.

I gave my Test Field the name "MessBox" and then added an OnClick event to the button to call the sndReq() JavaScript function. You can check out the two HTML lines at the code repository for this blog

Now add a second page to the project - The default name will be WebForm2.aspx which matches with the hard coded value you will have noticed in the sndReq() JavaScript function above - if you call your new page something else then you will have to adjust the http.open() line in that function.

Do not put any controls on the new page and for a first run just add the following to the PageLoad() sub in the "code behind".

Dim YouSent As String = Request.QueryString(0)
Response.Write("You sent " & YouSent)

Now let us have a quick look at the JavaScript. There is a good explanation of the function at the location linked at the top of this article so I can keep it simple here. The CreateRequestObject() function simply handles the fact that versions of Internet Explorer before version 7 have the XMLHTTPRequest object named as XMLHTTP - in fact this code will need adjustment if it is likely to run into a beta of IE7. The sndReq() function makes an asynchronous call to the specified URL and the handleResponse() function is registered as part of the sndReq() function as the function that will manage any returned responses.

Fire up the application and click the button. The alert() command added to the JavaScript handleResponse() function will show you exactly what comes back. You will see the expected message "you sent foo" followed by the HTML for the empty page - including (nearly) empty HEAD, FORM and BODY tags.

Just to get our first ASP.NET/Ajax app up and running we can make a couple of changes and then think about the implications of what just happened.

First - let's change the Response.Write line to

Response.Write("Hello World") as that was our original intention although it was nice to see that we could pass data to the server as well as retrieve it using our ultra simple Ajax functions.

Then open up WebPage2 in the HTML view and remove all of the code with the exception of the first line (the one that registers the Code Behind). This will stop the ASP.NET page adding it's HTML to the response - because there will be none to add. This can be done programmatically at run time but not from the page load event (as the HTML has not yet been rendered at that point in time).

Then run the application and click the button. We now have a working application that implements Ajax technology with requested data being displayed without reloading the page.

Clearly a more complex web page with multiple opportunities to implement Ajax technology would require a more sophisticated set-up at the client end. Also, while the technique shown could be easily amended to handle multiple requirements at the server end it is probable that you would want individual controls to communicate directly with prepared functions within the same page. In all probability you will want to move on to one of the Ajax control libraries or to implement something like the Ajax.dll file described in the MSDN article ASP.NET Spiced: Ajax that allows you to tag specified functions as "Ajax Methods" and call them from the client. I will take the opportunity to explore one or two of these options in this blog although I am traveling again for the next few days - to the USA this time

Wednesday, June 20, 2007

Sacrifice

The word "Sacrifice" is essential for every human life. If i say i am fine, definitely behind that my parents sacrifice. If a man wants become a complete person in this word he needs to sacrifice something in this world. I have such experience in my life is "When i was child age i think i was studying 6th standard. my villages were preparing to celebrate Christmas. But my family was not, because all are know Christmas comes last week of the december month, so my father haven’t money to purchase dresses and sweets. But me and my sisters expecting my father definitely purchase dresses for us, but the time was going 6pm,.. 7pm... 9pm, i did not understand my family position because i am small boy. Then me and my sister slept with Christmas dreams. After that my mother went to pawn broker and get money with mummy's chain from him and purchase dresses, next day morning when i got up from bed and i can see a gift pack near my pillow, i was really exiting to see what inside that gift pack. After opened that pack, my mother ask to me that how is the dress do you like? I answered “I like very much and thanks”. Then my family had good Christmas. Now I am realizing my father and mother sacrifice. So we try to make happy others.. and ourselves with sacrifice.

Monday, June 18, 2007

History

Learning history is so easy. But making history is so difficult. Make a history of yourself and make others to learn it.. SMS

Thursday, June 14, 2007

Role Model

Our life should be role model to others. Each and every of us have role model like a favorite actor, favorite film star or a historical person. My favorite role model is my team leader. There are many reasions for this. He is looking very smart, each and every his activities tells something. I have learned lot of things from him like how to behave to others in critial situation. Still i am learning from him. He is going to enter marraige life soon. I heartly wish him for bright and colurful married life in adanvance.
....Think Positive, ....Do Positive, ...Result must be possitive.

Wednesday, June 13, 2007

Introduce MySelf

Its my first blog, i feel very happy about this. I am a software engineer living in chennai.