Vous êtes sur la page 1sur 10

What is Ajax

AJAX stands for Asynchronous JavaScript And XML. It got famous through Gmail etc. It is a part of Web 2.0 Techniques which allows some part or the whole document to dynamically update without refreshing the whole web page. So the time taken to get the response from the server gets reduced as the pages are getting updated in the background through AJAX. Also it gives more interaction on the web page. It is a browser based technology and is independent of any Web Server Programming language. AJAX Acronym: A: A stands for Asynchronous mode. This technique allows the web page to make request in asynchronous/synchronous mode to the web server. By default in all the AJAX examples it is set to Asynchronous mode. The advantage of making it asynchronous is that is will allow the web page to make multiple calls at a same time which will work in the background and will update the page dynamically as soon the request gets over. J: J stands for JavaScript. AJAX extensively rely on JavaScript Engine for its functioning. So it is essential that the JavaScript should be enabled for AJAX to work. X: X stands for XML. AJAX uses the XMLHttpRequest Object of the JavaScript Engine. With this object it can also handle the request and response messages in XML Format apart fron traditional text format. Examples of AJAX based websites: www.gmail.com

Limitations of AJAX:

It can only access the page from the domain the original web page is coming from. i.e. demo.html residing at example.com can makes AJAX call to web page residing only at www.example.com.

Headache of AJAX Programming:


All the program will have to be written in JavaScript. So you must be an expert in JavaScript to write AJAX Programs. AJAX program should be compatible with different browsers DOM.

Lot of request goes to the server. So the server requires huge bandwidth to allocate the request made. Testing on different browsers. Sometimes if your servers fails to respond to the AJAX call then you will have to wait endlessly until you again make the AJAX call.

Before AJAX came into Picture:


IFRAME were used to display data of other webpage or other domain in the same page. The page inside the IFRAME can be reload/changed dynamically using Traditional JavaScript Technique.

How AJAX Works


The best way to learn this topic to understand the comparison between the traditional method of calling the Web page from the server and AJAX methodology.

Traditional WebPage Call


User interacts with the webpage to perform its operation The request is submitted to the Web Server along with the information user wants Server checks for the details and might require to interact with the Database and finally returns the response to the browser Browser displays the user response details in the form of refreshing the webpage

Traditional WebPage Call


User has to wait until the page reloads User can perform only one action at a time

AJAX come to the rescue:


With AJAX user can fetch the data from the server without refreshing the whole page. During AJAX call following steps are followed User interacts with the web page to perform its operation. At this point your webpage internally through JavaScript calls a remote file and the user data is passed through GET/POST method The web server receives the request processes it and send the data back to the client browser At this point the web page is not reloaded and the browser JavaScript engine is waiting for the response from the web server. The web page gets the response from the server and dynamically through JavaScript displays the content fetched from the server

Advantage of using AJAX:


Make multiple AJAX calls with different request from the same page Instant result Not to wait for the page to get reload

EXAMPLE
<html> <head> <title>Ajax and PHP Demo</title> <script type="text/javascript"> var xmlhttp = new getXMLObject(); var time_variable; function getXMLObject() //XML OBJECT { var xmlHttp = false; try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP") // For Old Microsoft Browsers } catch (e) { try { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") // For Microsoft IE 6.0+ } catch (e2) { xmlHttp = false // No Browser accepts the XMLHTTP Object then false } } if (!xmlHttp && typeof XMLHttpRequest != 'undefined') { xmlHttp = new XMLHttpRequest(); //For Mozilla, Opera Browsers } return xmlHttp; // Mandatory Statement returning the ajax object created } function ajaxFunction() { var getdate = new Date(); //Used to prevent caching during ajax call if(xmlhttp) { xmlhttp.open("GET","ajax_time.php?" + getdate.getTime(),true); xmlhttp.onreadystatechange = handleServerResponse; xmlhttp.send(null); } } function handleServerResponse() { if (xmlhttp.readyState == 4) { if(xmlhttp.status == 200) { document.myForm.time.value=xmlhttp.responseText; //Update the HTML Form element } else {

alert("Error during AJAX call. Please try again"); } } } </script> <body> <form name="myForm"> Server Time:<input type="text" name="time" /> <br /> <input type="button" onClick="javascript:ajaxFunction();" value="Click to display Server Time on Textbox"/> </form> </body> </head> </html>

Common AJAX Programming Mistakes


With the advent of Web 2.0 the Web Application has now become more interactive in nature thanks to AJAX. But this interactive using AJAX comes with some mistakes that people generally doesnt follows. Below are the list of mistakes that AJAX gives you as a gift.

No Back Button Functionality


By default the browser stores the web page visited in the History Folder, but with AJAX the browser is unable to retrieve the dynamic content.

2. Waiting Endlessly
The AJAX functionality largely depend on the network connection and the bandwidth. AJAX works well with good Internet Connection so if you are using dial-up you will have to wait until the response comes from the server. But if your browser get struck in between the AJAX call irrespective of the internet connection then your browser window is dead until the user reloads the page or opens a same page and writes the same content again and submit.

Using AJAX for the sake of AJAX.


AJAX is a very good feature to implement in todays web world but you also have to make count of the usability of it.

Cross Browser Compatible


If your web application is targeting multiple browser you will have to make sure that the AJAX Application works seamlessly on all the browsers.

Browsers Load
Making too much AJAX calls will degrade the browser performance and it will become slow. This will make the user experience horrible for your site.

Bookmarking
Users cannot bookmark the page having dynamic content fetched using AJAX. The reason is AJAX will fetch dynamic data from the server and the bookmark link will only store the static data stored in the internet cache folder.

Enable/Disable JavaScript
AJAX purely works with JavaScript and if the users browsers has JavaScript disabled then the AJAX functionality will not work.

FAQ on AJAX Technology


AJAX has become an hot technology with Web2.0 but before starting AJAX Programming developers needs to know some important FAQ on AJAX. Q) Ajax an Microsoft Technology? A) Absolutely No, Ajax is an cross browser technology. It is browser dependent and uses JavaScript. Q)Are Ajax applications easier to develop than traditional web applications? A) Not necessarily. Ajax applications can involve complex JavaScript code on the client. To develop that complex code efficient and bug-free is not an simple task as it involves pure JavaScript & DHTML coding. But better development tools and frameworks are require to make the Ajax Application development much faster and easier. Q) Do Ajax applications always deliver a better experience than traditional web applications? A) Not necessarily. Ajax gives interaction designers more flexibility. However, the more power we have, the more caution we must use in exercising it. We must be careful to use Ajax to enhance the user experience of our applications, not degrade it. Q) Apart from AJAX any other Technique exist for Dynamic Web Page Update? A) IFRAMES Q) Can AJAX access Server side script residing on different domain?

A) NO. Ajax can only access the Script residing on same domain. If you try to access the script from other domain browsers gives an error Access Denied Q) Ajax can also fetch XML content from server side, if this is true how? A) Using responseXML properties and then by using JavaScript XML DOM to access the attributes and value of XML data. Q) Is Ajax is Browser Dependent? A) Yes, Ajax object is part of JavaScript engine inside every browser. So if a new browser comes into market and the JavaScript engine doesnt have XMLHTTP object then Ajax will not work. Q) How can i check the progress of my Ajax call? A) When making Ajax call the readystate has to reach 4 to capture the remote date. So you can insert appropriate messages until the readystate reaches 4. Q) Do i have to wait endlessly after making Ajax Call? A) Not always but there are some exceptional cases when the remote server is already busy and is unable to handle your request in that case the JavaScript code will wait until response is fetched from the remote server or there is browser request timed out. You can use the interval to make another call after specific interval. Q) Do i have to explicitly use Ajax Frameworks for implementing Ajax? A) Not necessarily, Ajax Frameworks are meant to make the life of programmers simpler. These frameworks acts as an wrapper to the Ajax Code, they provide you with the function call that will do all the Ajax Call and you dont have to write the Basic Ajax Code. Q) Can Ajax work with all Web Technologies? A) Yes, Ajax is browser dependent and if the web technology you are using supports browser then Ajax will work. Q) Can i make multiple Ajax Call? A) Yes you can make multiple Ajax call provided you have separate Ajax Object variables created. Making another Ajax Call on the existing Ajax Object will overwrite the previous make call. Q) Can i do Ajax Connection Pooling Techniques? A) Yes you can do connection pooling for making Ajax call. Here you will be storing all the Ajax objects in a connection pool so that every individual object will perform their own task.

Ajax Programming Part 1


This tutorial will guide you on the basic of AJAX programming and how to write code for running AJAX based application. There is a 5 step approach for the browser to work with AJAX.

Initialize the XMLHttpRequest Object Opening the connection to the remote server side script Define the function handler Send the request back to the server Receive the data from the server through the handler

Step1 Initialize the XMLHttpRequest Object:


Every browser has a different way to initialize the XMLHttpObject. For example Microsft Browsers treat them as a ActiveX Object where as other browsers like Firefox, Mozilla, Opera, Netscape etc treat them as a XMLHttp Object. Defining XMLHttpRequest Object in Internet Explorer:
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); Depending on the browser version it will take appropriate ActiveX Object. Here we are creating a new ActiveXObject and assigning it to xmlHttp variable. More details on XMLHttp Object is covered on Basics of AJAX Part 2 Defining XMLHttpRequest Object in Mozilla, Firefox, Opera Browsers: xmlHttp = new XMLHttpRequest();

Here we are creating a new Object instance of the XMLHttpRequest and assigning it to xmlHttp variable.

Step2 Opening the connection to the remote server side script


After successfully creating the AJAX object you now try to call the remote script. Methods inside XMLHttp Object for Connection: .open(methodname,remote filename,mode of operation) Responsible for opening the connection to the remote server. method It can be GET or POST depending on the amount of data you want to send to the server. remote filename Server path of the remote file name. mode of operation Accepts a boolean value indication Async/Sync mode of operation. True indicates Asynchrounous Mode whereas False indicated Synchronous Mode.

Example .open(): xmlHttp.open("GET","demo.php",true); Here i am calling demo.php using GET method with asynchronous operation.

Step3 Define the function handler on change of every state


During AJAX operation while connecting to the remote script, the server returns various states value which indicates the current state of operation. So we have to define a function that will take care of the states and after the response is complete fetch all the data and display it. Example: xmlhttp.onreadystatechange = handleServerResponse; Here i am defining handleServerResponse as the callback function for every change in state. There are 4 different states that the web server will return in AJAX call.
readyState Description 0 1 2 3 4 Initialized loading loaded Some interactive with the server (Complete Data not available) Complete

Step4 Send off a request to the server:


This step will tell the Ajax Object to send the request back to the Web Server.
xmlhttp.send(null); xmlhttp.send(param); //GET METHOD //POST METHOD

In GET Method you pass all the data along with the url in .open() method. In POST Method you pass all the data along with the variable inside send method.
Step5 Receive the data from the server through the function handler

You will get all your data back from the server from the function handler function. You will need to check for ready state before capturing the data.
function handleServerResponse() { if(xmlhttp.readystate == 4) {

if(xmlhttp.status == 200) { //Perform your operation } } else { //Loading state or show error message } }

The above code tells the JavaScript Engine to process further only when the readystate == 4. Also inside we check for status which gives me the HTTP Status. If both the condition matches then proceed further and perform your operation. If the ready state does not matches then you can display Loading State until it reaches 4.

Ajax Programming Part 2 In the previous article we discussed on the concept of coding and methods getting used in Ajax Operation. In this we will go deep inside the XMLHttp Object and other issues on AJAX Programming.
XMLHttpRequest Object Methods: .open(methodname,url,mode

of operation) method It can be GET or POST depending on the amount of data you want to send to the server. url Server path of the remote file name. mode of operation Accepts a boolean value indication Async/Sync mode of operation. True indicates Asynchrounous Mode whereas False indicated Synchronous Mode .send(parameter) In case of POST method send all the values as a parameter to the send method .abort() Abort the current AJAX call operation .getAllResponseHeaders() Returns all the header(labels & values) as a string .getResponseHeader(Header Name) Returns the value of the specified header name .setRequestHeader(label,value) Set the Header before sending the request

XMLHttpRequest Object Properties:


.onreadystatechange Event handler that gets fires at each state change .status Returns the HTTP status from the server .responseText Return the response data in string format from the server .responseXML Return the response data in XML format from the server

Example of using GET Method xmlhttp.open("GET",url,true) xmlhttp.send(null) Example of using POST Method xmlhttp.open("POST",url, true); xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded;charset=UTF-8;'); xmlhttp.send('hello=world&XMLHttpRequest=test');

Here we setting the header for application data having character set as UTF-8. Also we are sending two variable hello and XMLHttpRequest having values world and test.

Limitations of AJAX:

Sending data through querystring has limitation on number of characters so need to be careful while sending data. Needs to be decided in advance before sending data to the server If same AJAX object variable is used to call remote script then the old remote server call gets lost and is replaced by the server call. The solution to this problem is to used different variable for every ajax operation or implement a queue facility

Caching in AJAX
Browsers caches the data send through GET methods (i.e through querystring in Temporary Internet Folder). To overcome this situation following methods can be used.
mellifluous

Add the timestamp in the querystring Use POST method so the variable will get processed at server end

Vous aimerez peut-être aussi