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 Code:
<?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 Code:
<?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
