Dynadot

Easy Startup Guide for AJAX

NameSilo
Watch
Impact
68
Hi all,

I have been learning Ajax lately and found that this is actually not a difficult technique to dive in and it is very useful for adding new web2.0 fuctions to our current sites. I have compiled the following summary to help any new developers to head start their learning of AJAX.

What is AJAX

AJAX stands for Asynchronous JavaScript and XML. It is actually more of a technique as it utilize the XMLHttpRequest object in the common browsers.

What is AJAX used for

AJAX is mainly used to load a partial webpage to display updated content rather than the conventional GET / POST methods where the whole page is reloaded. The advantage in loading a partial section of a web page is that user can still see the other content of a page while the AJAX is working. Some common applications that utilize AJAX currently is Gmail and NetFlix.

An Easy Example

The following example illustrate a user press a button on the form and the server will response and display the details of the newest member.

1st step: Creating the XMLHttpRequest Object

The first step we do is to create the XMLHttpRequest Object (XHR) so that AJAX can work. The following codes are meant for creating this instance:
Code:
function GetXmlHttpObject()
{ 
var objXMLHttp=null
if (window.XMLHttpRequest)
{
objXMLHttp=new XMLHttpRequest()
}
else if (window.ActiveXObject)
{
objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
}
return objXMLHttp
}
The above function will create the XHR. The reason why there is an if loop is that some browsers do not support ActiveX objects such as Firefox, as it implements XHR as a native JavaScript object. Therefore, the above codes will cover all cases.

2nd step: Coding the main function

Code:
function testajax()
{
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request")
return
} 
var url="pulldata.php"
xmlHttp.onreadystatechange=stateChanged 
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}
The main function will first test if the browser supports XHR, if not, end execution. We have three new properties here namely, onreadystatechange, open and send. Allow me to explain the flow:

1. The variable url, contains the URL to the file that does the processing of the queries like database abstraction. In our case, the file is coded in PHP. You can use any server-side scripting you prefer :)

2. onreadytstatechange will be triggered based on the application status. For example, it will trigger stateChanged() function once it has finished loading or is loading. I will explain this in the next step.

3. open will send the queries to the URL. In our case, we use the GET method to pass to the URL as stated. The true value means that this request is asynchronously. True is the default value.

4. send simply sends the request to the server.

3rd step: Detailing the stateChanged function

Our stateChanged function is as follows:
Code:
function stateChanged() 
{ 
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") document.getElementById("show").innerHTML=xmlHttp.responseText 

if (xmlHttp.readyState==1 || xmlHttp.readyState=="loading") document.getElementById("show").innerHTML="<div align=center>Loading...</div>"
}
We have two loops here. As I have mentioned before, this function will be triggered whenever the request returns a new status. In the above example, we will show the user a "Loading.." notification once the application starts loading. Upon completion of the whole request, it will display the results in the show container.

4th step: Finishing up with the Server Side

Our pulldata.php looks like:
PHP:
<?php
//select from database the latest records

//save the data into the result[]

//output the respective results 
echo'The latest member is: '.$results["name"].' ';
?>
This whole string will be passed back to the client side through the responseText property and displayed in the page subsequently.

Final Step: Event triggerer

We will have to decide how are we going to intial this request. Is it through a form button? Or a link?
I have illustrated a trigger by a press on the button below:
Code:
<form action="#">
<input type="button" value="View the newest member" onclick="testajax();" />
</form>

Putting all together
In total, we have two files, our main page and the server processing file.

Main Page:
Code:
<html>
<head></head>
<script type="text/javascript">

var xmlHttp
function GetXmlHttpObject()
{ 
var objXMLHttp=null
if (window.XMLHttpRequest)
{
objXMLHttp=new XMLHttpRequest()
}
else if (window.ActiveXObject)
{
objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
}
return objXMLHttp
}

function testajax()
{
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request")
return
} 
var url="pulldata.php"
xmlHttp.onreadystatechange=stateChanged 
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
} 

function stateChanged() 
{ 
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") document.getElementById("show").innerHTML=xmlHttp.responseText 

if (xmlHttp.readyState==1 || xmlHttp.readyState=="loading") document.getElementById("show").innerHTML="<div align=center>Loading...</div>"
} 
</script>
<body>

<form action="#">
<input type="button" value="View the newest member" onclick="testajax();" />
</form>

<div id="show"></div>

</body></html>

pulldata.php
PHP:
<?php
//select from database the latest records

//save the data into the result[]

//output the respective results 
echo'The latest member is: '.$results["name"].' ';
?>
You have just knew how to code an AJAX application :)

Other Important Information

1. My example uses responseText to display the server's output. Alternatively, you can use XML (responseXML) as output and have your client parse the results and display appropriately.

2. My example did not send any parameters to the server. This can be easily done by appending the URL before sending the request to the server and have the processing script grabbing the parameters via GET. You can also use POST to send your parameters to the server. Refer to the following resources for more info.

Other Useful Resources
The following are some of the top sites that contains very useful information about AJAX:

1. http://ajaxpatterns.org/Main_Page - The main source of AJAX knowledge!

2. http://ajaxian.com/ -Useful information for reference.

3. http://ajaxblog.com/ -Another great site for AJAX examples.

4. http://www.ajaxload.info/ -Contains tons of useful loading images for free use.

Enjoy this AJAX :tu:
 
Last edited:
2
•••
The views expressed on this page by users and staff are their own, not those of NamePros.
Nice tut! Thanks AbsoluteKC.

I've been looking for a basic tut on AJAX, haven't looked at AJAX much yet.

Rep added, thanks again.
 
0
•••
Now this is called digested content.

I liked it a lot. Will play around with this and hoping will create some nice web applications if my brains support me.

Thanks. Rep Added.
 
0
•••
Great resources! Thanks AbsoluteKC. Rep added.
 
0
•••
Does that differencate browsers... firefox or ie.. because i believe firefox uses a different techniue for the refresh
 
0
•••
templaterave said:
Does that differencate browsers... firefox or ie.. because i believe firefox uses a different techniue for the refresh
The example is compatible in all browsers that support:

1. XmlHttpRequest object
2. JavaScript

The main concept behind AJAX is the XHR object. Therefore, it works the same in IE and FF etc.
 
0
•••
0
•••
-Nick- said:
Now this is called digested content.
Tottally agree!

Very interesting as well!

Thanks for sharing!
 
0
•••
  • The sidebar remains visible by scrolling at a speed relative to the page’s height.
Back