How AJAX Works
How AJAX Works
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.
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.
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
User has to wait until the page reloads User can perform only one action at a time
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>
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.
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.
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.
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
Here we are creating a new Object instance of the XMLHttpRequest and assigning it to xmlHttp variable.
Example .open(): xmlHttp.open("GET","demo.php",true); Here i am calling demo.php using GET method with asynchronous operation.
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
.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