AJAX TUTORIAL 1. WHAT IS AJAX? AJAX is short for Asynchronous JavaScript and XML. AJAX is based on JavaScript and HTTP requests. AJAX is not a new programming language, but a new way to use existing standards. AJAX is the art of trading data with a web server, and changing parts of a web page, without reloading the whole page. AJAX is not a new programming language, but a new technique for creating better, faster, and more interactive web applications. With AJAX, a JavaScript can communicate directly with the server, with the XMLHttpRequest object. With this object, a JavaScript can trade data with a web server, without reloading the page. AJAX uses asynchronous data transfer (HTTP requests) between the browser and the web server, allowing web pages to request small bits of information from the server instead of whole pages. The AJAX technique makes Internet applications smaller, faster and more user-friendly. 2. AJAX uses the XMLHttpRequest object To get or send information from/to a database or a file on the server with traditional JavaScript, you will have to make an HTML form, and a user will have to click the "Submit" button to send/get the information, wait for the server to respond, then a new page will load with the results. Because the server returns a new page each time the user submits input, traditional web applications can run slowly and tend to be less user-friendly. With AJAX, your JavaScript communicates directly with the server, through the JavaScript XMLHttpRequest object. With the XMLHttpRequest object, a web page can make a request to, and get a response from a web server - without reloading the page. The user will stay on the same page, and he or she will not notice that scripts request pages, or send data to a server in the background. 3. The XMLHttpRequest object By using the XMLHttpRequest object, a web developer can update a page with data from the server after the page has loaded! AJAX was made popular in 2005 by Google (with Google Suggest). Google Suggest is using the XMLHttpRequest object to create a very dynamic web interface: When you start typing in Google's search box, a JavaScript sends the letters off to a server and the server returns a list of suggestions. The XMLHttpRequest object is supported in all major browsers (Internet Explorer, Firefox, Chrome, Opera, and Safari). 4. A Sample
Click to let AJAX change this text
5. Two important methods of XMLHttpRequest To send a request to a web server, we use the open() and send() methods. 5.1. open() The open() method takes three arguments. The first argument defines which method to use (GET or POST). The second argument specifies the name of the server resource (URL). The third argument specifies if the request should be handled asynchronously. 5.2. send() The send() method sends the request off to the server. If we assume that requested a file called "time.asp", the code would be: url="time.asp"; //absolute path or relative path xmlhttp.open("GET",url,true); xmlhttp.send(null); In the example we assume that the current web page and the requested resource are both in the same file directory. 6. Two important properties of XMLHttpRequest The XMLHttpRequest object has 3 important properties: The responseText property The readyState property The onreadystatechange property 6.1. responseText The XMLHttpRequest object stores any data retrieved from a server as a result of a server request in its responseText property. In the previous chapter we copied the content of the responsText property into our HTML with the following statement: document.getElementById('test').innerHTML=xmlhttp.responseText
6.1.1 XMLHttpRequest Open - Using False In the examples (from the previous pages) we used this simplified syntax: xmlhttp.open("GET",url,false);//'false' tells tells the XMLHttpRequest object to wait until the server request is completed before next statement is executed. xmlhttp.send(null); document.getElementById('test').innerHTML=xmlhttp.responseText; For small applications and simple server request, this might be OK. But if the request takes a long time or cannot be served, this might cause your web application to hang or stop.
6.1.2 XMLHttpRequest Open - Using True By changing the third parameter in the open call to "true", you tell the XMLHttpRequest object to continue the execution after the request to the server has been sent. Because you cannot simply start using the response from the server request before you are sure the request has been completed, you need to set the onreadystatechange property of the XMLHttpRequest, to a function (or name of a function) to be executed after completion. In this onreadystatechange function you must test the readyState property before you can use the result of the server call. Simply change the code to: xmlhttp.onreadystatechange=function(){ if(xmlhttp.readyState==4) { document.getElementById('test').innerHTML=xmlhttp.responseText } } xmlhttp.open("GET",url,true); xmlhttp.send(null);
6.2. readyState The readyState property The readyState property holds the status of the server's response. Possible values for the readyState property: State Description 0 The request is not initialized 1 The request has been set up 2 The request has been sent 3 The request is in process 4 The request is complete
6.3. onreadystatechange The onreadystatechange property stores a function (or the name of a function) to be called automatically each time the readyState property changes. You can store a full function in the property like this: xmlhttp.onreadystatechange=function() { if(xmlhttp.readyState==4) {document.getElementById('test').innerHTML=xmlhttp.responseText} } xmlhttp.open("GET",url,true); xmlhttp.send(null); Or you can store the name of a function like this: xmlhttp.onreadystatechange=state_Change; xmlhttp.open("GET",url,true); xmlhttp.send(null); ... function state_Change() { if(xmlhttp.readyState==4) {document.getElementById('test').innerHTML=xmlhttp.responseText} } 7. XMLHttpRequest Object can Request any Data With the XMLHttpRequest object, you can request any web resource from a server. You can request TXT files, HTML files, XML files, pictures or any data that is accessible from the Internet. AJAX is about creating clever applications that can use the data. -------------------------------------------------------------------------------- Requesting Text Files Many AJAX applications requests pure text files to retrieve data for the application. -------------------------------------------------------------------------------- Requesting XML Files A very common AJAX method is to request XML files to retrieve application data. -------------------------------------------------------------------------------- Requesting ASP or PHP Files Requesting an ASP or PHP file is the most common way to access database information. -------------------------------------------------------------------------------- Requesting HTML Files Requesting HTML files is a common method for filling out different information on a web page -------------------------------------------------------------------------------- Submitting Forms With AJAX you can easily submit form data without having to reload the page. 8. AJAX Suggest example The following AJAX example will demonstrate how a web page can communicate with a web server while a user enters data into an HTML form. -------------------------------------------------------------------------------- The AJAX HTML page This is the HTML page. It contains a simple HTML form and a link to a JavaScript.
Suggestions:
-------------------------------------------------------------------------------- The AJAX JavaScript This is the JavaScript code, stored in the file "clienthint.js":
var xmlhttp function showHint(str) { if (str.length==0) { document.getElementById("txtHint").innerHTML=""; return; } xmlhttp=GetXmlHttpObject(); if (xmlhttp==null) { alert ("Your browser does not support XMLHTTP!"); return; } var url="gethint.asp"; url=url+"?q="+str; url=url+"&sid="+Math.random(); xmlhttp.onreadystatechange=stateChanged; xmlhttp.open("GET",url,true); xmlhttp.send(null); }
function stateChanged() { if (xmlhttp.readyState==4) { document.getElementById("txtHint").innerHTML=xmlhttp.responseText; } } //The purpose of the GetXmlHttpObject() function is to solve the problem of creating different XMLHTTP objects for different browsers: function GetXmlHttpObject() { if (window.XMLHttpRequest){ // code for IE7+, Firefox, Chrome, Opera, Safari return new XMLHttpRequest(); } if (window.ActiveXObject){ // code for IE6, IE5 return new ActiveXObject("Microsoft.XMLHTTP"); } return null; } --------------------------------------------------------------------------------
The AJAX server page - ASP and PHP There is no such thing as an AJAX server. AJAX pages can be served by any internet server.
The server page called by the JavaScript in the example from the previous chapter is a simple ASP file called "gethint.asp".
Below we have listed two examples of the server page code, one written in ASP and one in PHP.