rohan
In the zone
AJAX tutorial [2nd Part now updated!!!]
*img423.imageshack.us/img423/8035/ajaxpageheader4oz.jpg
Prologue: The thing that is AJAX
NOTE: Some innaccuracies have been noted in this article, corrections to whom are given in a further post[post #38]. Please scroll to that post or Click Here
For the 2nd part, please check further posts in this thread or go here: *www.thinkdigit.com/forum/showpost.php?p=252530&postcount=15
AJAX is one the those things which are re-invented only to find that this time they have become the biggest show-stealers and the hottest topics for forums, blogs and various sites. Basically, what is AJAX. AJAX as you may know, stands for Asynchronus JavaScript And XML. The fullform is useless because it is hardly close to the definition pertaining to which I've made this tutorial. AJAX, is a technology or a method which enables a web-page to contact the server from within the page without causing the browser to load any other page, reloading or any sort of redirection. By 'contact' the server I mean, to contact the server with params and in return get data.
Buying books on AJAX is useless. AJAX is not a topic so vast that it requires a book. There is a lot of filler-stuff filled in those books like "AJAX and bandwidth", "What AJAX can do", "What AJAX can't do". This is just an author's attempt to reach to the 'word-limit' for their works to be called 'books'. Out of it, 70% of the information everyone knows, and for the rest, no one wants to know that.
Prologue 2: Getting down to AJAX
So.. let's get down to some AJAX. AJAX consisits of two parts:
1. Server side
2. Client Side
Server Side is coded via php, asp, jsp etc. In this tutorial, we'll use php and MySQL. Client-side is obviously JavaScript. We will also be using a fair amount of xHTML as it is necessary for defining our pages.
The tools you need are:
1. A text-editor
2. A browser supporting XMLHttpRequest()
3. php and MySQL installed on your system + a webserver(recommended: Apache 2.xx)
4. Basic knowledge of: JavaScript, php, SQL and (x)HTML
There are two ways of scripting AJAX:
1. XMLHttpRequest()
2. iFrames
iFrames method is not reliable and an iFrame cannot be controlled once it is set to fetch a server side request. Hence, we will be using XMLHttpRequest(). The browsers supporting it are:
1. Internet Explorer 6+ (through ActiveX)
2. Opera 8+
3. Firefox 1.00+
There are other browsers, but I am not aware whether or not they support this method. Please check your browser if it supports XMLHttpRequest().
Chapter 1: The grounds of our app
Let's first start with a generic xHTML page:
Now, let's create a script object for inserting the AJAX code. Here is the modified <head> section of our HMTL page:
Now, we come to the server-side. Here is the generic php code for outputting a simple string "AJAX was here":
Now things are setup, we can go into AJAX.
Chapter 2: The XMLHttpRequest() object
The XMLHttpRequest() is a JavaScript object. It has the following methods:
It has the following event(s):
P.S: Actually, onReadyStateChange is a property of the object which has the value of the function which is to be executed when the request is available.
It has the following properties:
If I have confused by now.. please forgive me. All this will be simplified as we go into scripting AJAX.
Chapter 3: The createRequestObject() function
We will now make our first steps towards AJAX scripting. A new XMLHttpRequest() object can be made quite simply:
The browser wars have made things quite difficult for use developers. Hence we need to do a bit of work to overcome these problems. Opera and Firefox have no problems with this method. But we just cannot afford to neglect the people using Internet Explorer because it's user base is so huge, that neglecting means reducing your client base drastically. Internet Explorer uses XMLHttpRequest via ActiveX control. Hence, we will make a function in JavaScript that makes the XMLHttpRequest according to the browser. Here is the createRequestObject():
What this function does is, firstly it initializes two variables: xhr and browser. Then using the appName property of the 'navigator' object, it determines the name of the browser. Then it checks whether the current browser supports XMLHttpRequest or not. If it supports, then it assigns the value 'xhr' as a new XMLHttpRequest. If not, it checks if the browser is Internet Explorer. If it is, then it attempts to create an ActiveXObject called the XMLHTTP, which is actually similar to the XMLHttpRequest. Otherwise, it alerts the user that the page cannot be viewed on their browser. Now, in both the cases, xhr is the XMLHttpRequest object. In the final statement, we return the object called 'xhr'. So, now we can create an XMLHttpRequest like this:
Simple, ain't it?? Now we've learnt to make an XMLHttpRequest object across browsers easily. Let's move on to some real AJAX now...
Chapter 4: Doing some AJAX
Now, let's move to some practical things. Let's do some AJAX. This basic example here will be a simple example. You click a button, the server is contacted and a string is returned. We will be using the code written in Chapter 1 as part of the setup.
4.1: The HTML page
This is the sample page we will use for dispalying this AJAX example:
Save this file as ajaxmain.html and the php file as returndata.php. Your page should look like this:
*img423.imageshack.us/img423/7599/basicexample1yn.gif
Try it on your server and see if it works or not. If you don't know php, you can try it with any other server side scripting language you know. If you don't know php, you can try this with a file too. For example, in the code just replace 'returndata.php' with the file of your choice. The contents of your file will be the responseText of the htppr object. Now, let us dissect the code and understand what it is..
Note: If you are using php or any server scripting, be sure to access these files through the server (via *localhost or *127.0.0.1)
4.2: Cracking the code
The function createRequestObject() is already clear to you. What we do in this script is we first, make a variable called httpr and make it a XMLHttpRequest() object through our createRequestObject() function. Then using the onclick="javascript:fetchData()" HTML attrib, the function fetchData() is accessed whenever you click on the button labelled 'Click to change text'. The fetchData() function is very useful. This is what it does, line-by-line:
1. Initialize the XMLHttpRequest. The first param i.e 'GET' is the method of data transfer. We will be using GET for know as POST is used for transferring files and passwords(secure data). But, I will add that in the 2nd part of the tutorial.
2. Change the onreadystatechange (all small letters. JavaScript is absurdly case-sensitive) property to the function name you want to execute whenever it is available. In our case, it is processData(). Remember, we don't write it as httpr.onreadystatechange = processData() but we write it as httpr.onreadystatechange = processData. This is because the '()' are put only when calling or declaring a function. When assigning function to a property, we use the function as a variable, hence we don't put the two brackets and even if we do, it won't work.
3. We finally send the request.
This was the anatomy of a simple XMLHttpRequest() example. Now, let us dig into the processData() function for the final steps. Here is what the processData() function does when it is called line-by-line.
1. Obviously, this function is called whenever the readyState of the request changes. Firstly, it checks if the readyState of the httpr object is 4. If not, nothing happens.
2. If it is 4, then it checks for the status of the httpr object. If it is 200, then it continues, otherwise again.. nothing happens. (You can add custom checks for a 404 status(page not-found error), 500 status(internal server error), 403 status(Forbidden Access error) etc.).
3. If everything's fine, it initializes a variable called 'data' and assigns it all that it has recieved from the request using the httpr.responseText property.
4. Finally, using generic JavaScript methods, we change the text of an HTML element with the id called 'fields' from whatever it was to whatever we got from the request.
The HTML code must be quite familiar to you and I need not explain that as I told you: You need basic knowledge of JavaScript for this tutorial.
Note: If you might have wondered why the variable httpr was declared out of everything... it was because the variable was to be used by two functions. Hence it needed to be a global variable. Had I decalred it inside the fetchData() function, it would have died the minute fetchData() was over and processData() wouldn't have been able to use it even if it had been alive.
Chapter 5: Some Trivia
I wanted to pack in another neater example.. but I'll do it on 5th June because of time constrains. Out of whatever I've taught you, this is most if the AJAX you'll ever use. If you are puzzled where the XML went.. let me tell you that I am against the idea of using XML for AJAX. There are two reasons for that:
1. If even one character of the XML data is not reached due to a communication failure or whatsoever, the parser would give a failure and you won't be able to get any message. But, if you use text like we have used in this message, you can atleast get some data from it. AJAX if not wisely used is a bandwidth killer. Hence, you need to make the most out of your request returns.
2. Supposing you have to get the data of a name and phone no. from the server. This is the XML way of doing it, so that the parser will parse it without any problems:
3. XML Parsers are sometimes slow and change as browsers change. Using AJAX libraries is another bad option as they are too complicated for their purposes.
Whereas you can also put it as text: Somename|123456|Agoodname|789012 and then take the odd text-pieces as names and even text-pieces as numbers seperated by a pipe i.e '|'. The first case used 176 characters, while the 2nd case uses only 32 characters. As I said.. bandwidth is necessary.
As for the trivia, data strings like the one above is usable. This is how:
This way you can easily use this information. If needed you can make the server script to append a string called '|FEH' to all request returns. Then on the client side, you can check if the last element in the array is 'FEH'. If it is, then data has not been truncated on the way. Isn't it much better than XML Parsers?
You can use these methods for login systems, forum replies and what not. You can make the script print a 1 or 0 if the login passes or fails. Then on computing the returns, you can easily make out whether the login was succesfull or not. However, never use AJAX for security sensitive applications.
Epilogue: Thanks a lot
I hope you liked the tutorial. There is a lot coming in the next parts of this tutorial:
1. An ellaborate example for creating a phonebook system powered by AJAX.
2. Using AJAX for POST applications.
3. Sending file with AJAX.
That was all from my side. Thanks for reading this tutorial. Questions, doubts and queries are welcome.
©Rohan Prabhu. mailto:rohan2kool@gmail.com
*img423.imageshack.us/img423/8035/ajaxpageheader4oz.jpg
Prologue: The thing that is AJAX
NOTE: Some innaccuracies have been noted in this article, corrections to whom are given in a further post[post #38]. Please scroll to that post or Click Here
For the 2nd part, please check further posts in this thread or go here: *www.thinkdigit.com/forum/showpost.php?p=252530&postcount=15
AJAX is one the those things which are re-invented only to find that this time they have become the biggest show-stealers and the hottest topics for forums, blogs and various sites. Basically, what is AJAX. AJAX as you may know, stands for Asynchronus JavaScript And XML. The fullform is useless because it is hardly close to the definition pertaining to which I've made this tutorial. AJAX, is a technology or a method which enables a web-page to contact the server from within the page without causing the browser to load any other page, reloading or any sort of redirection. By 'contact' the server I mean, to contact the server with params and in return get data.
Buying books on AJAX is useless. AJAX is not a topic so vast that it requires a book. There is a lot of filler-stuff filled in those books like "AJAX and bandwidth", "What AJAX can do", "What AJAX can't do". This is just an author's attempt to reach to the 'word-limit' for their works to be called 'books'. Out of it, 70% of the information everyone knows, and for the rest, no one wants to know that.
Prologue 2: Getting down to AJAX
So.. let's get down to some AJAX. AJAX consisits of two parts:
1. Server side
2. Client Side
Server Side is coded via php, asp, jsp etc. In this tutorial, we'll use php and MySQL. Client-side is obviously JavaScript. We will also be using a fair amount of xHTML as it is necessary for defining our pages.
The tools you need are:
1. A text-editor
2. A browser supporting XMLHttpRequest()
3. php and MySQL installed on your system + a webserver(recommended: Apache 2.xx)
4. Basic knowledge of: JavaScript, php, SQL and (x)HTML
There are two ways of scripting AJAX:
1. XMLHttpRequest()
2. iFrames
iFrames method is not reliable and an iFrame cannot be controlled once it is set to fetch a server side request. Hence, we will be using XMLHttpRequest(). The browsers supporting it are:
1. Internet Explorer 6+ (through ActiveX)
2. Opera 8+
3. Firefox 1.00+
There are other browsers, but I am not aware whether or not they support this method. Please check your browser if it supports XMLHttpRequest().
Chapter 1: The grounds of our app
Let's first start with a generic xHTML page:
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "*www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="*www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="content-type" content="text/html" />
<title>My first AJAX page</title>
</head>
<body>
<p>Hello world</p>
</body>
</html>
Now, let's create a script object for inserting the AJAX code. Here is the modified <head> section of our HMTL page:
Code:
<head>
<script type="text/javascript">
<!--
//Our code comes here
//-->
</script>
</head>
Now, we come to the server-side. Here is the generic php code for outputting a simple string "AJAX was here":
Code:
<?php
printf("AJAX was here");
?>
Now things are setup, we can go into AJAX.
Chapter 2: The XMLHttpRequest() object
The XMLHttpRequest() is a JavaScript object. It has the following methods:
Code:
XMLHttpRequest.abort() -> Abort the XMLHttpRequest request
XMLHttpRequest.getAllResponseHeaders() -> Get all the headers from XMLHttpRequest request to the server
XMLHttpRequest.getResponseHeader() -> Get only the 'status' and 'readyState' headers from XMLHttpRequest request to the server
XMLHttpRequest.open() -> Open(Initialize) a XMLHttpRequest()
XMLHttpRequest.send() -> Execute the XMLHttpRequest()
It has the following event(s):
Code:
XMLHttpRequest.onReadyStateChange -> Event executes whenever the request is available.
P.S: Actually, onReadyStateChange is a property of the object which has the value of the function which is to be executed when the request is available.
It has the following properties:
Code:
XMLHttpRequest.readyState: The readyState header from the request. It has 4 possible values:
0 Uninitialized: The object has not been initialized yet.
1 Open: The open() method has been succesfully called
2 Sent: The data has been sent, but the request return is yet awaited
3 Receiving: The request data is now available
XMLHttpRequest.responseText: The text outputted by the server
XMLHttpRequest.responseXML: Same as the above with the only difference that it has a content-type text/xml
XMLHttpRequest.status: Http status of the XMLHttpRequest(). Example -> 200(Page found without any http errors), 404(Not found), 500(Internal Server Error) etc.
If I have confused by now.. please forgive me. All this will be simplified as we go into scripting AJAX.
Chapter 3: The createRequestObject() function
We will now make our first steps towards AJAX scripting. A new XMLHttpRequest() object can be made quite simply:
Code:
//JavaScript code
myAjax = new XMLHttpRequest();
//or the syntax can be said to be:
(object) = new XMLHttpRequest();
The browser wars have made things quite difficult for use developers. Hence we need to do a bit of work to overcome these problems. Opera and Firefox have no problems with this method. But we just cannot afford to neglect the people using Internet Explorer because it's user base is so huge, that neglecting means reducing your client base drastically. Internet Explorer uses XMLHttpRequest via ActiveX control. Hence, we will make a function in JavaScript that makes the XMLHttpRequest according to the browser. Here is the createRequestObject():
Code:
<script type="text/javascript">
<!--
function createRequestObject() {
var xhr;
var browser = navigator.appName;
if(!window.XMLHttpRequest){
if(browser == "Microsoft Internet Explorer") {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert("Sorry, this page cannot be viewed on your browser i.e " + browser);
return false;
}
} else {
xhr = new XMLHttpRequest();
}
return xhr;
}
//-->
</script>
What this function does is, firstly it initializes two variables: xhr and browser. Then using the appName property of the 'navigator' object, it determines the name of the browser. Then it checks whether the current browser supports XMLHttpRequest or not. If it supports, then it assigns the value 'xhr' as a new XMLHttpRequest. If not, it checks if the browser is Internet Explorer. If it is, then it attempts to create an ActiveXObject called the XMLHTTP, which is actually similar to the XMLHttpRequest. Otherwise, it alerts the user that the page cannot be viewed on their browser. Now, in both the cases, xhr is the XMLHttpRequest object. In the final statement, we return the object called 'xhr'. So, now we can create an XMLHttpRequest like this:
Code:
//JavaScript code
myAjax = createRequestObject();
Simple, ain't it?? Now we've learnt to make an XMLHttpRequest object across browsers easily. Let's move on to some real AJAX now...
Chapter 4: Doing some AJAX
Now, let's move to some practical things. Let's do some AJAX. This basic example here will be a simple example. You click a button, the server is contacted and a string is returned. We will be using the code written in Chapter 1 as part of the setup.
4.1: The HTML page
This is the sample page we will use for dispalying this AJAX example:
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "*www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="*www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859" />
<title>My first AJAX page</title>
<script type="text/javascript">
<!--
var httpr = createRequestObject();
function createRequestObject() {
var xhr;
var browser = navigator.appName;
if(!window.XMLHttpRequest){
if(browser == "Microsoft Internet Explorer") {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert("Sorry, this page cannot be viewed on your browser i.e " + browser);
return false;
}
} else {
xhr = new XMLHttpRequest();
}
return xhr;
}
function fetchData() {
httpr.open('GET', 'returndata.php');
httpr.onreadystatechange = processData;
httpr.send(null);
}
function processData() {
if(httpr.readyState == 4) {
if(httpr.status == 200) {
var data = httpr.responseText;
document.getElementById('fields').innerHTML = data;
}
}
}
//-->
</script>
</head>
<body>
<p id="fields">Text here will be changed</p>
<input type="button" value="Click to change text" onclick="javascript:fetchData()" />
</body>
</html>
Save this file as ajaxmain.html and the php file as returndata.php. Your page should look like this:
*img423.imageshack.us/img423/7599/basicexample1yn.gif
Try it on your server and see if it works or not. If you don't know php, you can try it with any other server side scripting language you know. If you don't know php, you can try this with a file too. For example, in the code just replace 'returndata.php' with the file of your choice. The contents of your file will be the responseText of the htppr object. Now, let us dissect the code and understand what it is..
Note: If you are using php or any server scripting, be sure to access these files through the server (via *localhost or *127.0.0.1)
4.2: Cracking the code
The function createRequestObject() is already clear to you. What we do in this script is we first, make a variable called httpr and make it a XMLHttpRequest() object through our createRequestObject() function. Then using the onclick="javascript:fetchData()" HTML attrib, the function fetchData() is accessed whenever you click on the button labelled 'Click to change text'. The fetchData() function is very useful. This is what it does, line-by-line:
1. Initialize the XMLHttpRequest. The first param i.e 'GET' is the method of data transfer. We will be using GET for know as POST is used for transferring files and passwords(secure data). But, I will add that in the 2nd part of the tutorial.
2. Change the onreadystatechange (all small letters. JavaScript is absurdly case-sensitive) property to the function name you want to execute whenever it is available. In our case, it is processData(). Remember, we don't write it as httpr.onreadystatechange = processData() but we write it as httpr.onreadystatechange = processData. This is because the '()' are put only when calling or declaring a function. When assigning function to a property, we use the function as a variable, hence we don't put the two brackets and even if we do, it won't work.
3. We finally send the request.
This was the anatomy of a simple XMLHttpRequest() example. Now, let us dig into the processData() function for the final steps. Here is what the processData() function does when it is called line-by-line.
1. Obviously, this function is called whenever the readyState of the request changes. Firstly, it checks if the readyState of the httpr object is 4. If not, nothing happens.
2. If it is 4, then it checks for the status of the httpr object. If it is 200, then it continues, otherwise again.. nothing happens. (You can add custom checks for a 404 status(page not-found error), 500 status(internal server error), 403 status(Forbidden Access error) etc.).
3. If everything's fine, it initializes a variable called 'data' and assigns it all that it has recieved from the request using the httpr.responseText property.
4. Finally, using generic JavaScript methods, we change the text of an HTML element with the id called 'fields' from whatever it was to whatever we got from the request.
The HTML code must be quite familiar to you and I need not explain that as I told you: You need basic knowledge of JavaScript for this tutorial.
Note: If you might have wondered why the variable httpr was declared out of everything... it was because the variable was to be used by two functions. Hence it needed to be a global variable. Had I decalred it inside the fetchData() function, it would have died the minute fetchData() was over and processData() wouldn't have been able to use it even if it had been alive.
Chapter 5: Some Trivia
I wanted to pack in another neater example.. but I'll do it on 5th June because of time constrains. Out of whatever I've taught you, this is most if the AJAX you'll ever use. If you are puzzled where the XML went.. let me tell you that I am against the idea of using XML for AJAX. There are two reasons for that:
1. If even one character of the XML data is not reached due to a communication failure or whatsoever, the parser would give a failure and you won't be able to get any message. But, if you use text like we have used in this message, you can atleast get some data from it. AJAX if not wisely used is a bandwidth killer. Hence, you need to make the most out of your request returns.
2. Supposing you have to get the data of a name and phone no. from the server. This is the XML way of doing it, so that the parser will parse it without any problems:
Code:
<?xml version="1.0" encoding="iso-8859-1"?>
<person>
<name>Somename</name>
<phone>123456</phone>
</person>
<person>
<name>Agoodname</name>
<phone>789012</phone>
</person>
3. XML Parsers are sometimes slow and change as browsers change. Using AJAX libraries is another bad option as they are too complicated for their purposes.
Whereas you can also put it as text: Somename|123456|Agoodname|789012 and then take the odd text-pieces as names and even text-pieces as numbers seperated by a pipe i.e '|'. The first case used 176 characters, while the 2nd case uses only 32 characters. As I said.. bandwidth is necessary.
As for the trivia, data strings like the one above is usable. This is how:
Code:
var data = "Somename|123456|Agoodname|789012"; //You can also get this via a httpr.responseText
var strings = new Array();
var phones = new Array();
strings = data.split('|');
/*Split the string into text-pieces seperated by a pipe symbol
for(var i=0; i<=strings.length; i++) {
/*if it's even, it's a phone no., if it's odd... it's a name*/
if(i%2 == 0) {
phones[] = strings[i];
} else {
names[] = strings[i];
}
}
This way you can easily use this information. If needed you can make the server script to append a string called '|FEH' to all request returns. Then on the client side, you can check if the last element in the array is 'FEH'. If it is, then data has not been truncated on the way. Isn't it much better than XML Parsers?
You can use these methods for login systems, forum replies and what not. You can make the script print a 1 or 0 if the login passes or fails. Then on computing the returns, you can easily make out whether the login was succesfull or not. However, never use AJAX for security sensitive applications.
Epilogue: Thanks a lot
I hope you liked the tutorial. There is a lot coming in the next parts of this tutorial:
1. An ellaborate example for creating a phonebook system powered by AJAX.
2. Using AJAX for POST applications.
3. Sending file with AJAX.
That was all from my side. Thanks for reading this tutorial. Questions, doubts and queries are welcome.
©Rohan Prabhu. mailto:rohan2kool@gmail.com
Last edited: