AJAX Asynchronous Java Script and XML AJAX is

  • Slides: 38
Download presentation
AJAX (Asynchronous Java. Script and XML. ) • AJAX is not a new programming

AJAX (Asynchronous Java. Script and XML. ) • AJAX is not a new programming language, but a new way to use existing standards. • AJAX is the art of exchanging data with a server, and updating parts of a web page - without reloading the whole page. • The goal of Ajax is to provide Web –based applications with responsiveness approaching that desktop applications. • Non ajax tech , The rendering of new page takes time for both network latency and rendering time (speed) • In non ajax web-application , even the smallest change in the displayed document may requires the same processes that produced the initial display. • The browser is locked and user can do nothing but wait. • In AJAx the browser does not need to locked while its wait for the response. The user can continue to do with the browser • AJAX meant to increase the web page's interactivity, speed, and usability.

What is AJAX? • AJAX = Asynchronous Java. Script and XML. • AJAX is

What is AJAX? • AJAX = Asynchronous Java. Script and XML. • AJAX is a technique for creating fast and dynamic web pages. • AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page. • Classic web pages, (which do not use AJAX) must reload the entire page if the content should change. • Examples of applications using AJAX: Google Maps, Gmail, Youtube, and Facebook tabs.

 • Ajax uses XHTML for content and CSS for presentation, as well as

• Ajax uses XHTML for content and CSS for presentation, as well as the Document Object Model and Java. Script for dynamic content display. • Ajax helps you in making your web application more interactive by retrieving small amount of data from web server and then showing it on your application. You can do all these things without refreshing your page.

How AJAX Works

How AJAX Works

Cont. . • When user first visits the page, the Ajax engine is initialized

Cont. . • When user first visits the page, the Ajax engine is initialized and loaded. From that point of time user interacts with Ajax engine to interact with the web server. • The Ajax engine operates asynchronously while sending the request to the server and receiving the response from server. • Ajax life cycle within the web browser can be divided into follow ing stages • 1. User Visit to the page: User visits the URL by typing URL in browser or clicking a link from some other page • 2. Initialization of Ajax engine: When the page is initially loaded, the Ajax engine is also initialized. The Ajax engine can also be set to continuously refresh the page content without refreshing the whole page.

Cont … 3. Event Processing Loop: Ø Browser event may instruct the Ajax engine

Cont … 3. Event Processing Loop: Ø Browser event may instruct the Ajax engine to send request to server and receive the response data Ø Server response - Ajax engine receives the response from the server. Then it calls the Java. Script call back functions Ø Browser (View) update - Java. Script request call back functions is used to update the browser. DHTML and CSS is used to update the browser display.

AJAX is Based on Internet Standards and uses a combination of: • XMLHttp. Request

AJAX is Based on Internet Standards and uses a combination of: • XMLHttp. Request object (to exchange data asynchronously with a server) • Java. Script/DOM (to display/interact with the information) • CSS (to style the data) • XML (often used as the format for transferring data) • AJAX applications are browser- and platformindependent! • AJAX was made popular in 2005 by Google, with Google Suggest.

Following are techniques used in the Ajax applications • Java. Script: Java. Script is

Following are techniques used in the Ajax applications • Java. Script: Java. Script is used to make a request to the web server. Once the response is returned by the webserver, more Java. Script can be used to update the current page. DHTML and CSS is used to show the output to the user. Java. Script is used very heavily to provide the dynamic behavior to the application. • Asynchronous Call to the Server: Most of the Ajax application used the XMLHttp. Request object to send the request to the web server. These calls are Asynchronous and there is no need to wait for the response to come back. User can do the normal work without any problem. • XML: XML may be used to receive the data returned from the web server. Java. Script can be used to process the XML data returned from the web server easily.

AJAX Browser Support • • • Mozilla Firefox 1. 0 and above Netscape version

AJAX Browser Support • • • Mozilla Firefox 1. 0 and above Netscape version 7. 1 and above Apple Safari 1. 2 and above. Microsoft Internet Exporer 5 and above Konqueror Opera 7. 6 and above

Steps of AJAX Operation 1. 2. 3. 4. A client event occurs An XMLHttp.

Steps of AJAX Operation 1. 2. 3. 4. A client event occurs An XMLHttp. Request object is created The XMLHttp. Request object is configured The XMLHttp. Request object makes an asynchronous request to the Webserver. 5. Webserver returns the result containing XML document. 6. The XMLHttp. Request object calls the callback() function and processes the result. 7. The HTML DOM is updated

To understand how AJAX works, we will create a small AJAX application • The

To understand how AJAX works, we will create a small AJAX application • The AJAX application above contains one div section and one button. • The div section will be used to display information returned from a server. • The button calls a function named load. XMLDoc(), if it is clicked:

Example <!DOCTYPE html> <body> <div id="my. Div"><h 2>Let AJAX change this text</h 2></div> <button

Example <!DOCTYPE html> <body> <div id="my. Div"><h 2>Let AJAX change this text</h 2></div> <button type="button" onclick="load. XMLDoc()">Change Content</button> </body> </html> Next, add a <script> tag to the page's head section. The script section contains the load. XMLDoc() function

Cont. . <head> <script> function load. XMLDoc() {. . AJAX script goes here. .

Cont. . <head> <script> function load. XMLDoc() {. . AJAX script goes here. . . } </script> </head>

 • AJAX - Create an XMLHttp. Request Object • The keystone of AJAX

• AJAX - Create an XMLHttp. Request Object • The keystone of AJAX is the XMLHttp. Request object. The XMLHttp. Request Object • All modern browsers support the XMLHttp. Request object (IE 5 and IE 6 use an Active. XObject). • The XMLHttp. Request object is used to exchange data with a server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.

Create an XMLHttp. Request Object All modern browsers (IE 7+, Firefox, Chrome, Safari, and

Create an XMLHttp. Request Object All modern browsers (IE 7+, Firefox, Chrome, Safari, and Opera) have a built-in XMLHttp. Request object. Syntax for creating an XMLHttp. Request object: variable=new XMLHttp. Request(); Old versions of Internet Explorer (IE 5 and IE 6) uses an Active. X Object: variable=new Active. XObject("Microsoft. XMLHTTP"); To handle all modern browsers, including IE 5 and IE 6, check if the browser supports the XMLHttp. Request object. If it does, create an XMLHttp. Request object, if not, create an Active. XObject:

Cont. . • XMLHttp. Request (XHR) is an API that can be used by

Cont. . • XMLHttp. Request (XHR) is an API that can be used by Java. Script, JScript, VBScript and other web browser scripting languages to transfer and manipulate XML data to and from a web server using HTTP, establishing an independent connection channel between a web page's Client-Side and Server-Side. • The XMLHttp. Request object is the key to AJAX

<!DOCTYPE html> <head> <script> function load. XMLDoc() { var xmlhttp; if (window. XMLHttp. Request)

<!DOCTYPE html> <head> <script> function load. XMLDoc() { var xmlhttp; if (window. XMLHttp. Request) {// code for IE 7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttp. Request(); } else {// code for IE 6, IE 5 xmlhttp=new Active. XObject("Microsoft. XMLHTTP"); } xmlhttp. onreadystatechange=function() { if (xmlhttp. ready. State==4 && xmlhttp. status==200) { document. get. Element. By. Id("my. Div"). inner. HTML=xmlhttp. response. Text; } } xmlhttp. open("GET", "ajax_info. txt", true); xmlhttp. send(); } </script>

 • . </head> <body> <div id="my. Div"><h 2>Let AJAX venkata rami reddy</h 2></div>

• . </head> <body> <div id="my. Div"><h 2>Let AJAX venkata rami reddy</h 2></div> <button type="button" onclick="load. XMLDoc()">Change Content</button> </body> </html>

XMLHttp. Request Methods • • abort() Cancels the current request. get. All. Response. Headers()

XMLHttp. Request Methods • • abort() Cancels the current request. get. All. Response. Headers() Returns the complete set of HTTP headers as a string. get. Response. Header( header. Name ) Returns the value of the specified HTTP header. open( method, URL ) open( method, URL, async, user. Name, password ) Specifies the method, URL, and other optional attributes of a request. The method parameter can have a value of "GET", "POST", or "HEAD". Other HTTP methods, such as "PUT" and "DELETE" (primarily used in REST applications), may be possible The "async" parameter specifies whether the request should be handled asynchronously or not. "true" means that script processing carries on after the send() method, without waiting for a response, and "false" means that the script waits for a response before continuing script processing.

Cont. . • send( content ) Sends the request. • set. Request. Header( label,

Cont. . • send( content ) Sends the request. • set. Request. Header( label, value ) Adds a label/value pair to the HTTP header to be sent

XMLHttp. Request Properties • onreadystatechange An event handler for an event that fires at

XMLHttp. Request Properties • onreadystatechange An event handler for an event that fires at every state change. • ready. State The ready. State property defines the current state of the XMLHttp. Request object. Here are the possible values for the ready. State property: 0 1 2 3 4 State 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 completed

Ø ready. State=0 after you have created the XMLHttp. Request object, but before you

Ø ready. State=0 after you have created the XMLHttp. Request object, but before you have called the open() method. Ø ready. State=1 after you have called the open() method, but before you have called send(). Ø ready. State=2 after you have called send(). Ø ready. State=3 after the browser has established a communication with the server, but before the server has completed the response. Ø ready. State=4 after the request has been completed, and the response data have been completely received from the server.

 response. Text Returns the response as a string. • response. XML Returns the

response. Text Returns the response as a string. • response. XML Returns the response as XML. This property returns an XML document object, which can be examined and parsed using W 3 C DOM node tree methods and properties • status Returns the status as a number (e. g. 404 for "Not Found" and 200 for "OK"). • status. Text Returns the status as a string (e. g. "Not Found" or "OK").

AJAX - Send a Request To a Server • xmlhttp. open("GET", "ajax_info. txt", true);

AJAX - Send a Request To a Server • xmlhttp. open("GET", "ajax_info. txt", true); xmlhttp. send(); • Method Description open(method, url, async) Specifies the type of request, the URL, and if the request should be handled asynchronously or not. method: the type of request: GET or POST url: the location of the file on the server async: true (asynchronous) or false (synchronous) send(string) : Sends the request off to the server. string: Only used for POST requests

GET or POST? • GET is simpler and faster than POST, and can be

GET or POST? • GET is simpler and faster than POST, and can be used in most cases. • However, always use POST requests when: Ø A cached file is not an option (update a file or database on the server) Ø Sending a large amount of data to the server (POST has no size limitations) Ø Sending user input (which can contain unknown characters), POST is more robust and secure than GET

GET Requests • Ex: xmlhttp. open("GET", "demo_get. asp", true); xmlhttp. send(); Ø To avoid

GET Requests • Ex: xmlhttp. open("GET", "demo_get. asp", true); xmlhttp. send(); Ø To avoid this, add a unique ID to the URL: • xmlhttp. open("GET", "demo_get 2. asp? fname=Henry &lname=Ford", true); xmlhttp. send(); Ø If you want to send information with the GET method, add the information to the URL: • xmlhttp. open("GET", "demo_get 2. asp? fname=Henry&lname=Ford", true); xmlhttp. send();

POST Requests • Example • xmlhttp. open("POST", "demo_post. asp", true); xmlhttp. send(); Ø To

POST Requests • Example • xmlhttp. open("POST", "demo_post. asp", true); xmlhttp. send(); Ø To POST data like an HTML form, add an HTTP header with set. Request. Header(). Specify the data you want to send in the send() method: • xmlhttp. open("POST", "ajax_test. asp", true); xmlhttp. set. Request. Header("Content-type", "application/x-wwwform-urlencoded"); xmlhttp. send("fname=Henry&lname=Ford");

XML file • AJAX can be used for interactive communication with an XML file.

XML file • AJAX can be used for interactive communication with an XML file.

<html> <body> <script type="text/javascript" > function ajaxfunction() { var xmlhttp; if(window. XMLHttp. Request) {

<html> <body> <script type="text/javascript" > function ajaxfunction() { var xmlhttp; if(window. XMLHttp. Request) { xmlhttp=new XMLHttp. Request(); } else { xmlhttp=new Active. XObject("Microsoft. XMLHTTP"); } xmlhttp. onreadystatechange=function() { if(xmlhttp. ready. State==4) { document. timeform. time. value=xmlhttp. response. Text; } } xmlhttp. open("GET", "Simple. Ajax. php", true); xmlhttp. send(null); } </script> <form name="timeform" > Name: <input type="text" name="Name" onkeyup="ajaxfunction()"; /> <br/> Time: <input type="text" name="time"/> </form> </body> </html>

Cont. . Simple. Ajax. php • <? php echo ($SERVER_ADDR); ? >

Cont. . Simple. Ajax. php • <? php echo ($SERVER_ADDR); ? >

Example

Example

<html> <head> <title>Simple Ajax Example</title> <script language="Javascript"> function post. Request(str. URL) { var xml.

<html> <head> <title>Simple Ajax Example</title> <script language="Javascript"> function post. Request(str. URL) { var xml. Http; if (window. XMLHttp. Request) { // Mozilla, Safari, . . . var xml. Http = new XMLHttp. Request(); }else if (window. Active. XObject) { // IE var xml. Http = new Active. XObject("Microsoft. XMLHTTP"); } xml. Http. open('POST', str. URL, true); xml. Http. set. Request. Header ('Content-Type', 'application/x-www-form-urlencoded'); xml. Http. onreadystatechange = function() { if (xml. Http. ready. State == 4) { updatepage(xml. Http. response. Text); } } xml. Http. send(str. URL); } function updatepage(str){ document. get. Element. By. Id("result"). inner. HTML = "<font color='red' size='5'>" + str + "</font>"; ; } function Say. Hello(){ var usr=window. document. f 1. username. value; var rnd = Math. random(); var url="sayhello. php? id="+rnd +"&usr="+usr; post. Request(url); } </script> </head>

<body> <h 1 align="center"><font color="#000080">Simple Ajax Example</font></h 1> <p align="center"><font color="#000080">Enter your name and

<body> <h 1 align="center"><font color="#000080">Simple Ajax Example</font></h 1> <p align="center"><font color="#000080">Enter your name and then press "Say Hello Button"</font></p> <form name="f 1"> <p align="center"><font color="#000080">  Enter your name: <input type="text" name="username" id="username"> <input value="Say Hello" type="button" onclick='Java. Script: Say. Hello()' name="showdate"></font></p> <div id="result" align="center"></div> </form> <div id=result></div> </body> </html>

sayhello. php. • <? $usr=$_GET["usr"]; ? > <p>Welcome <? =$usr? >!</p> <p>Request received on:

sayhello. php. • <? $usr=$_GET["usr"]; ? > <p>Welcome <? =$usr? >!</p> <p>Request received on: <? print date("l M d. S, Y, H: i: s"); ? > </p>

– sample. html <html> <head><title>welcome</title> <script language="javascript"> req. Obj=null; function varify(){ document. get. Element.

– sample. html <html> <head><title>welcome</title> <script language="javascript"> req. Obj=null; function varify(){ document. get. Element. By. Id("res"). inner. HTML="Checking"; if(window. XMLHttp. Request){ req. Obj=new XMLHttp. Request(); }else { req. Obj=new Active. XObject("Microsoft. XMLHTTP"); } req. Obj. onreadystatechange=process; req. Obj. open("POST", ". /a. jsp? id="+document. get. Element. By. Id("username"). value, true); req. Obj. send(null); } function process(){ if(req. Obj. ready. State==4){ document. get. Element. By. Id("res"). inner. HTML=req. Obj. response. Text; } } </script> </head> <body> <h 1>welcome to this application</h 1> <form method="get" action="first"> User Name<input type="text" name="t 1" id="username" onblur="varify(); "><span id="res">< /span><br/> Password<input type="text" name="t 2"><br/> <input type ="submit" value="Press"/> </form> </body> </html >

a. jsp • <% String user=request. get. Parameter("id"); try{Thread. sleep(5000); }catch(Exception e){} if(user. equals("abc")){

a. jsp • <% String user=request. get. Parameter("id"); try{Thread. sleep(5000); }catch(Exception e){} if(user. equals("abc")){ %> <font color="red" ><strong>User already exists</strong></font> <% }else{ %> <font color="green" ><strong>User name not available</strong></font> <% } %>

Advantages of AJAX • XMLHttp. Request - It is used for making requests to

Advantages of AJAX • XMLHttp. Request - It is used for making requests to the non-Ajax pages. It supports all kind of HTTP request type. • • IFrame - It can make requests using both POST and GET methods. It supports every modern browsers. It supports asynchronous file uploads • (Inline Frames (IFrames) are windows cut into your webpage that allow your visitor to view another page on your site or off your site without reloading the entire page. ) • Cookies - In spite of implementation difference among browsers it supports large number of browsers • The interface is much responsive, instead of the whole page, a section of the page is transferred at a time. • Waiting time is reduced • Traffic to and from the server is reduced.

Dis Adv. • XMLHttp. Request -In the older version of IE (5 & 6)

Dis Adv. • XMLHttp. Request -In the older version of IE (5 & 6) Active. X to be enabled, this feature is available in new browsers and latest version of few. • IFrame - Requests have to be asynchronous. The design of the Server pages must be compatible with IFrame requests There is an implementation difference among different browsers. Unnecessary history records can be left on the history record of the browser. Request size is increased due to the fact that data is URLencoded.