Issuu on Google+

Simple AJAX Tutorials

By Sriram .A.S. sriramdasty7@gmail.com


Contents 1. Introduction to AJAX 2. What you must know before 3. METHOD 4. The XMLHttpRequest Object 5. A closer look at XMLHttpRequest Object 6. XMLHttpRequest object Vs Browsers 7. AJAX in action


Introduction to AJAX AJAX stands for Asynchronous Javascript And XML. Such a technical name scares us much!! Analyzing it word by word, AJAX is related to Javascript and XML, but what does Asynchronous mean?? Lets take an example of “Create an account” page of gmail.com. In that page, we have username, password etc., fields. And when you enter any username and click “Check availability”, some miracle happens. The username is taken, checked whether is it taken already or not and based on the check, a reply is generated and is INSERTED inside the page WITHOUT THE PAGE BEING REFRESHED. This magic is done by AJAX, sending data secretly. In the forth coming tutorials, we will see how things are being done.


What you must know before Before starting AJAX, you should know these things:: 1. HTML 2. Javascript A basic knowledge of them is enough, like what are html tags, how to make a simple html page, how to make a simple script using javascript. If you don‟t know these things, I strongly recommend you to learn them first, because you cannot understand AJAX without these.

METHOD This is the most important concept that you must understand before starting the AJAX tutorials. A METHOD is the way in which one file sends information to other. Since this concept is important, we will deal it with few examples: Lets take this html form code: <form action=”something.php” method=”GET”> <input type=”text” name=”uname” /> So what does this mean?? This form sends the form elements to “something.php” file using GET method. A GET method looks like this


Something.php?uname=sriram Note that the form element “uname” is sent to something.php as an URL only. Which means that the sent data is visible as URL or in browser. There is one more METHOD called “POST” <form action=”something.php” method=”POST”> <input type=”text” name=”uname” /> Here the information is passed to something.php file as hidden, which means the browser will not show this information.

The XMLHttpRequest Object With AJAX, our JavaScript communicates directly with the server, through the JavaScript XMLHttpRequest object. It is the power of this object that the ajax sends/receives information to server/any server script without the page refresh. The request is made in the background and the user cannot see this.


Since our tutorials are much more inclined towards practical programming, further details about these things are left. After you see a simple program in AJAX, you will feel easy to write ajax codes even without having deep knowledge about these things.

A closer look at XMLHttpRequest Object

As we saw that XMLHttpObject is the secret of AJAX to do these magics, let us analyze this object in detail. This object has three properties: 1. onreadystatechange 2. readyState 3. responseText

I again want to tell you, don‟t be afraid of these terms. There is no theoretical knowledge needed to code AJAX scripts. Just carry on till the end of this tutorials, don‟t stop your lessons here thinking that you cant understand anything. If you are so new to this programming world, you may find it difficult. But don‟t stop. Carry on till the last word of this tutorials. I wanted to start with programming


directly, but since itâ&#x20AC;&#x;s a formal tutorials, I have to write these things. After this tutorial is over, you will surely make your own AJAX scripts.

Back into action, we will see these properties one by one:: 1. onreadystatechange property This property stores the function that is to be called after receiving the response from the server.

2. readyState property There are five states of a request: State 0 1 2 3 4

Description The request is not initialized The request has been set up The request has been sent The request is in process The request is complete

At this point it is essential to explain a small bit of php: Say we have a file called sriram.php with the following code:


<?php $name=$_GET[„uname‟]; echo “Hello “.$name; ?> And a request like this sriram.php?uname=dasarathy Please note: that a file name followed by question mark is a GET method, as I told before. Such a request can be obtained by $_GET[] method So, $_GET[„uname‟] will extract what ever we send to the php file with uname attribute. Here we have the data “dasarathy” as the value of “uname” and hence $_GET[„uname‟] will return “dasarathy”. So, $name becomes “dasarathy” And finally this php file will print Hello dasarathy echo is the printing statement of php. Similarly Sriram.php?uname=john Will give the output as Hello john Coming back to AJAX, these are four states of a request which will be explained as this tutorials ascends. But it is to be remembered that the


onreadystatechange propery calls the specific function whenever these is a state change. 3. responseText property This property returns the response message that the server gives.

XMLHttpObject Vs Browsers Now lets start with programming. We must create XMLHttpObject in javascript, thatâ&#x20AC;&#x;s our goal, but the problem is that the command to create this object differs from different web browsers. For example: For IE5,IE6 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); For Mozilla xmlhttp=new XMLHttpRequest(); So, we have to create a function in javascript which tests for the all possibilities. Hence we have the following function in action:


function createObject() { var xmlhttp; if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else if (window.ActiveXObject) { // code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } else { alert("Your browser does not support XMLHTTP!"); } } So, what we do here is we make a function called “createObject”(you can have any name you like) and we create a variable xmlhttp and try to initialize it to the XMLHttpObject object, just by trial and error method. And if the browser is so old or not popular, we alert a message that the AJAX is not supported.


After seeing the code, surely you will be afraid that AJAX is difficult. I again repeat, you can just copy this code and use it. No need to write it. This code is going to come in all AJAX scripts and that too the same code. So you can copy the code and paste it where ever needed. Just understand it, no need to memorize it. Till now we have created the XMLHttpObject, now we will proceed with an example and AJAX script in action::

AJAX in action Task: Make a html page which dynamically says “hello” without refresh, accepting a name. Files: Hello.html ajax.js Server.php Hello.html <html> <head> <title>AJAX Example</title> <script src="ajax.js"></script>


</head> <body> <input type="text" id="uname"></input> <input type="button" value="Click Me" onClick="ajaxFun()"></input> <div id="result"></div> </body> </html> Explanation: First we create a html page, including a javascript file â&#x20AC;&#x153;ajax.jsâ&#x20AC;? and contains an input box, button and a division. The button has an action when it is clicked by onClick method. Server.php <?php $name=$_GET['uname']; echo "Hello ".$name; ?> Explanation: This is the php code which we saw already. It accepts a name by the GET method and displays the output such that if the request is like Server.php?uname=sriram The output is


Hello sriram ajax.js // Get the HTTP Object function getHTTPObject(){ if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP"); else if (window.XMLHttpRequest) return new XMLHttpRequest(); else { alert("Your browser does not support AJAX."); return null; } } // Change the value of the result field function setOutput(){ if(httpObject.readyState == 4){ document.getElementById('result').innerHTML = httpObject.responseText; } } // AJAX Logic function ajaxFun(){ var str=document.getElementById('uname').value; var url="Server.php";


url=url+"?uname="+str; httpObject = getHTTPObject(); if (httpObject != null) { httpObject.open("GET", url, true); httpObject.send(null); httpObject.onreadystatechange = setOutput; } } var httpObject = null; Explanation: We will trace this from the html file. When the button is clicked, ajaxFun() is called. So, lets jump to ajaxFun() in javascript. 1. Variable str stores whatever we type in the input textbox, (uname attribute) 2. getHTTPObject() function gets the appropriate way to communicate with the XMLHttpResponse object depending upon the browser and stores the result in httpObject variable 3. If the variable httpObject returns â&#x20AC;&#x153;nullâ&#x20AC;? we conclude that ajax is not supported by the browser and stop further execution 4. Otherwise, we proceed in making the response Remember these things always:


a) We make the response b) We send the response to the server c) We receive the response text from the server 5. We make the response first, we create a variable called url and make it like url=”Server.php?uname=X” where X is whatever we type in the text box (uname attribute) Say if I type Sriram in the textbox, url will contain “Server.php?uname=Sriram” Finally the response is created. 6. Now, we access the property onreadystatechange of httpObject and it calls the function stateChanged whenever these is a state change. 7. Now states start changing from 0-4 depending on the action that ajax performs. 8. We open the url and send nothing. These two function open() and send() and beyond the scope of this tutorials. send(), sends some variable when POST method is used. This is rarely used in AJAX. And for us, simple GET method is enough. 9. Thus, we open the url and when the state becomes 4 that is, the request is sent to the server and the server returns the response, we insert the responseText into the html document


by using document.getElementById function of javascript. 10. Thus the AJAX works!! In our example, we discuss it step by step 1. We enter “sriram” in the textbox and click the button. 2. The httpObject object is created 3. str=”sriram” 4. url=”Server.php?uname=sriram” 5. And the php file is executed and the output text is (responseText) Hello sriram 6. This is inserted into <div></div> by the javascript function document.getElementById

This brings us to the end of AJAX tutorials, now that you got a basic idea of how ajax works, use your imagination and skills to develop better ajax scripts. I hope you will develop your own AJAX scripts.


END


Simple AJAX Tutorials