AJAX Keywords: • • • • •
JavaScript and XML Web browser technology Open web standards Browser and platform independent Better and faster Internet applications
•
XML and HTTP Requests
AJAX = Asynchronous JavaScript And XML AJAX is an acronym for Asynchronous JavaScript And XML. AJAX is not a programming language, but simply a development technique for creating interactive web applications. AJAX uses JavaScript to send and receive data between a web browser and a web server. The AJAX technique makes web pages more responsive by exchanging data with a server behind the scenes, instead of reloading an entire web page each time a user makes a change. With AJAX, web applications can be faster, more interactive, and more user friendly. AJAX uses an XMLHTTPRequest object to send data to a web server, and XML is commonly used as the format for receiving server data, although any format, including plain text, can be used. AJAX Is A Browser Technology AJAX is a technology that runs in your browser. It uses asynchronous data transfer between the browser and the web server, allowing web pages to request small bits of information from the server instead of whole pages. The technology makes Internet applications smaller, faster and more user friendly. AJAX is a web browser technology independent of web server software. AJAX Is Based On Open Standards AJAX is based on the following open standards: • • •
JavaScript XML HTML
•
CSS
The open standards used in AJAX are well defined, and supported by all major browsers. AJAX applications are browser and platform independent. (Cross-Platform, Cross-Browser technology) AJAX Is About Better Internet Applications Web applications have many benefits over desktop applications, they can reach a larger audience, they are easier to install and support, and easier to develop. However, Internet applications are not always as "rich" and user-friendly as traditional desktop applications. With AJAX, Internet applications can be made richer (smaller, faster, and easier to use). You Can Start Using AJAX Today There is nothing new to learn. AJAX is based on open standards. These standards have been used by most developers for several years. Most existing web applications can be rewritten to use AJAX technology instead of traditional HTML forms. AJAX Uses XML And HTTP Requests A traditional web application will submit input (using an HTML form) to a web server. After the web server has processed the data, it will return a completely new web page to the user. Because the server returns a new web page each time the user submits input, traditional web applications often run slowly and tend to be less user friendly. With AJAX, web applications can send and retrieve data without reloading the whole web page. This is done by sending HTTP Requests to the server, and by modifying only parts of the web page using JavaScript. The preferred way to communicate with the server is by sending data as XML (but other methods can be used). You will learn more about how this is done in the next chapters of this tutorial.
AJAX can be used to create more interactive applications. AJAX Example In the AJAX example below we will demonstrate how a web page can communicate with a web server online as a user enters data into a web form. Type a Name in the Box Below First Name: Suggestions: Example Explained - The HTML Form The form above has the following HTML code:
Suggestions: <span id="txtHint">
As you can see it is just a simple HTML form with an input field called "txt1". The paragraph below the form contains a span called "txtHint". The span is used as a placeholder for hints retrieved from the web server. When the user inputs data, a function called "showHint()" is executed. The execution of the function is triggered by the "onkeyup" event. In other words: Each time the user moves his finger away from a keyboard key inside the txt1 field, the function showHint is called. Example Explained - The showHint() Function The showHint() function is a very simple JavaScript function placed in the section of the HTML page. The function contains the following code: function showHint(str) { if (str.length > 0) { var url="gethint.asp?sid="+Math.random()+"&q="+str
xmlHttp=GetXmlHttpObject(stateChanged) xmlHttp.open("GET", url , true) xmlHttp.send(null) } else { document.getElementById("txtHint").innerHTML="" } } The function executes every time a character is entered in the input field. If there is some input in the text field (str.length > 0) the function executes the following: • • •
Creates an XMLHTTP object Sends an HTTP request to the file "gethint.asp" on the server Tells the XMLHTTP object to execute the stateChanged() function when the HTTP triggers a change.
Example Explained - The stateChanged() Function The stateChanged() function contains the following code: function stateChanged() { if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") { document.getElementById("txtHint").innerHTML=xmlHttp.responseText } } The stateChanged() function executes every time the state of the XMLHTTP object changes. When the state changes to 4 (or to "complete"), the content of the txtHint span is filled with the response text. AJAX Example - AJAX Source The source code below belongs to the AJAX example on the previous page. You can copy and paste it, and try it yourself. The AJAX HTML Page
This is the HTML page. It contains a simple HTML form and a link to a JavaScript. <script src="clienthint.js">
Suggestions: <span id="txtHint">
The JavaScript code is listed below. The AJAX JavaScript This is the JavaScript code, stored in the file "clienthint.js": var xmlHttp function showHint(str) { if (str.length > 0) { var url="gethint.asp?sid=" + Math.random() + "&q=" + str xmlHttp=GetXmlHttpObject(stateChanged) xmlHttp.open("GET", url , true) xmlHttp.send(null) } else { document.getElementById("txtHint").innerHTML="" } } function stateChanged() { if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") { document.getElementById("txtHint").innerHTML=xmlHttp.responseText } } function GetXmlHttpObject(handler) {
var objXmlHttp=null if (navigator.userAgent.indexOf("Opera")>=0) { alert("This example doesn't work in Opera") return } if (navigator.userAgent.indexOf("MSIE")>=0) { var strName="Msxml2.XMLHTTP" if (navigator.appVersion.indexOf("MSIE 5.5")>=0) { strName="Microsoft.XMLHTTP" } try { objXmlHttp=new ActiveXObject(strName) objXmlHttp.onreadystatechange=handler return objXmlHttp } catch(e) { alert("Error. Scripting for ActiveX might be disabled") return } } if (navigator.userAgent.indexOf("Mozilla")>=0) { objXmlHttp=new XMLHttpRequest() objXmlHttp.onload=handler objXmlHttp.onerror=handler return objXmlHttp } }
The AJAX Server Page The server page called by the JavaScript, is a simple ASP file called "gethint.asp". The page is written in VBScript for an Internet Information Server (IIS). It could easily be rewritten in PHP, or some other server language. It just checks an array of names and returns the corresponding names to the client: <% dim a(30) a(1)="Anna" a(2)="Brittany"
a(3)="Cinderella" a(4)="Diana" a(5)="Eva" a(6)="Fiona" a(7)="Gunda" a(8)="Hege" a(9)="Inga" a(10)="Johanna" a(11)="Kitty" a(12)="Linda" a(13)="Nina" a(14)="Ophelia" a(15)="Petunia" a(16)="Amanda" a(17)="Raquel" a(18)="Cindy" a(19)="Doris" a(20)="Eve" a(21)="Evita" a(22)="Sunniva" a(23)="Tove" a(24)="Unni" a(25)="Violet" a(26)="Liza" a(27)="Elizabeth" a(28)="Ellen" a(29)="Wenche" a(30)="Vicky" q=ucase(request.querystring("q")) if len(q)>0 then hint="" for i=1 to 30 if q=ucase(mid(a(i),1,len(q))) then if hint="" then hint=a(i) else hint=hint & " , " & a(i) end if end if next end if if hint="" then response.write("no suggestion") else response.write(hint) end if %>
AJAX can be used for interactive communication with a database. AJAX Database Example In the AJAX example below we will demonstrate how a web page can fetch information from a database using AJAX technology. Select a Name in the Box Below Select a Customer: Customer info will be listed here. AJAX Example Explained The example above contains a simple HTML form and a link to a JavaScript: <script src="selectcustomer.js">
Customer info will be listed here.
As you can see it is just a simple HTML form with a drop down box called "customers". The paragraph below the form contains a div called "txtHint". The div is used as a placeholder for info retrieved from the web server. When the user selects data, a function called "showCustomer()" is executed. The execution of the function is triggered by the "onchange" event. In other words: Each time the user change the value in the drop down box, the function showCustomer is called. The JavaScript code is listed below.
The AJAX JavaScript This is the JavaScript code stored in the file "selectcustomer.js": var xmlHttp function showCustomer(str) { var url="getcustomer.asp?sid=" + Math.random() + "&q=" + str xmlHttp=GetXmlHttpObject(stateChanged) xmlHttp.open("GET", url , true) xmlHttp.send(null) } function stateChanged() { if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") { document.getElementById("txtHint").innerHTML=xmlHttp.responseText } } function GetXmlHttpObject(handler) { var objXmlHttp=null if (navigator.userAgent.indexOf("Opera")>=0) { alert("This example doesn't work in Opera") return } if (navigator.userAgent.indexOf("MSIE")>=0) { var strName="Msxml2.XMLHTTP" if (navigator.appVersion.indexOf("MSIE 5.5")>=0) { strName="Microsoft.XMLHTTP" } try { objXmlHttp=new ActiveXObject(strName) objXmlHttp.onreadystatechange=handler return objXmlHttp } catch(e) { alert("Error. Scripting for ActiveX might be disabled") return } } if (navigator.userAgent.indexOf("Mozilla")>=0)
{ objXmlHttp=new XMLHttpRequest() objXmlHttp.onload=handler objXmlHttp.onerror=handler return objXmlHttp } }
The AJAX Server Page The server paged called by the JavaScript, is a simple ASP file called "getcustomer.asp". The page is written in VBScript for an Internet Information Server (IIS). It could easily be rewritten in PHP, or some other server language. The code runs an SQL against a database and returns the result as an HTML table: sql="SELECT * FROM CUSTOMERS WHERE CUSTOMERID=" sql=sql & request.querystring("q") set conn=Server.CreateObject("ADODB.Connection") conn.Provider="Microsoft.Jet.OLEDB.4.0" conn.Open(Server.Mappath("/db/northwind.mdb")) set rs = Server.CreateObject("ADODB.recordset") rs.Open sql, conn response.write("
") do until rs.EOF for each x in rs.Fields response.write("" & x.name & " | ") response.write("" & x.value & " |
") next rs.MoveNext loop response.write("
")