1 / 38

AJAX ( Asynchronous JavaScript and XML .)

AJAX ( Asynchronous JavaScript 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.

adelle
Download Presentation

AJAX ( Asynchronous JavaScript and XML .)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. AJAX (Asynchronous JavaScript 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.

  2. What is AJAX? • AJAX = Asynchronous JavaScript 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.

  3. Ajax uses XHTML for content and CSS for presentation, as well as the Document Object Model and JavaScript 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. 

  4. How AJAX Works

  5. 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.

  6. 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 JavaScript call back functions • Browser (View) update - JavaScript request call back functions is used to update the browser. DHTML and CSS is used to update the browser display.

  7. AJAX is Based on Internet Standards and uses a combination of: • XMLHttpRequest object (to exchange data asynchronously with a server) • JavaScript/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 platform-independent! • AJAX was made popular in 2005 by Google, with Google Suggest.

  8. Following are techniques used in the Ajax applications • JavaScript:JavaScript is used to make a request to the web server. Once the response is returned by the webserver, more JavaScript can be used to update the current page. DHTML and CSS is used to show the output to the user. JavaScript is used very heavily to provide the dynamic behavior to the application. • Asynchronous Call to the Server:Most of the Ajax application used the XMLHttpRequest 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. JavaScript can be used to process the XML data returned from the web server easily.

  9. 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

  10. Steps of AJAX Operation • A client event occurs • An XMLHttpRequest object is created • The XMLHttpRequest object is configured • The XMLHttpRequest object makes an asynchronous request to the Webserver. • Webserver returns the result containing XML document. • The XMLHttpRequest object calls the callback() function and processes the result. • The HTML DOM is updated

  11. 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 loadXMLDoc(), if it is clicked:

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

  13. Cont .. <head><script>function loadXMLDoc(){.... AJAX script goes here ...}</script> </head>

  14. AJAX - Create an XMLHttpRequest Object • The keystone of AJAX is the XMLHttpRequest object. The XMLHttpRequest Object • All modern browsers support the XMLHttpRequest object (IE5 and IE6 use an ActiveXObject). • The XMLHttpRequest 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.

  15. Create an XMLHttpRequest Object All modern browsers (IE7+, Firefox, Chrome, Safari, and Opera) have a built-in XMLHttpRequest object. Syntax for creating an XMLHttpRequest object: variable=new XMLHttpRequest(); Old versions of Internet Explorer (IE5 and IE6) uses an ActiveX Object: variable=new ActiveXObject("Microsoft.XMLHTTP"); To handle all modern browsers, including IE5 and IE6, check if the browser supports the XMLHttpRequest object. If it does, create an XMLHttpRequest object, if not, create an ActiveXObject:

  16. Cont .. • XMLHttpRequest (XHR) is an API that can be used by JavaScript, 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 XMLHttpRequest object is the key to AJAX

  17. <!DOCTYPE html> <html> <head> <script> function loadXMLDoc() { varxmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","ajax_info.txt",true); xmlhttp.send(); } </script>

  18. </head> <body> <div id="myDiv"><h2>Let AJAX venkataramireddy</h2></div> <button type="button" onclick="loadXMLDoc()">Change Content</button> </body> </html> • .

  19. XMLHttpRequest Methods • abort()Cancels the current request. • getAllResponseHeaders()Returns the complete set of HTTP headers as a string. • getResponseHeader( headerName )Returns the value of the specified HTTP header. • open( method, URL )open( method, URL, async )open( method, URL, async, userName )open( method, URL, async, userName, 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.

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

  21. XMLHttpRequest Properties • onreadystatechangeAn event handler for an event that fires at every state change. • readyState The readyState property defines the current state of the XMLHttpRequest object. Here are the 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 completed

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

  23. responseTextReturns the response as a string. • responseXMLReturns the response as XML. This property returns an XML document object, which can be examined and parsed using W3C DOM node tree methods and properties • statusReturns the status as a number (e.g. 404 for "Not Found" and 200 for "OK"). • statusTextReturns the status as a string (e.g. "Not Found" or "OK").

  24. 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 POSTurl: the location of the file on the serverasync: true (asynchronous) or false (synchronous) send(string) : Sends the request off to the server.string: Only used for POST requests

  25. 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

  26. 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_get2.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_get2.asp?fname=Henry&lname=Ford",true);xmlhttp.send();

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

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

  29. <html><body><script type="text/javascript" >function ajaxfunction(){varxmlhttp; if(window.XMLHttpRequest) {xmlhttp=new XMLHttpRequest(); } else {xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }xmlhttp.onreadystatechange=function() { if(xmlhttp.readyState==4) {document.timeform.time.value=xmlhttp.responseText; } }xmlhttp.open("GET","SimpleAjax.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>

  30. Cont .. SimpleAjax.php • <?php  echo ($SERVER_ADDR);?>

  31. Example

  32. <html> <head> <title>Simple Ajax Example</title> <script language="Javascript"> function postRequest(strURL) { varxmlHttp; if (window.XMLHttpRequest) { // Mozilla, Safari, ... varxmlHttp = new XMLHttpRequest(); }else if (window.ActiveXObject) { // IE varxmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlHttp.open('POST', strURL, true); xmlHttp.setRequestHeader ('Content-Type', 'application/x-www-form-urlencoded'); xmlHttp.onreadystatechange = function() { if (xmlHttp.readyState == 4) { updatepage(xmlHttp.responseText); } } xmlHttp.send(strURL); } function updatepage(str){ document.getElementById("result").innerHTML = "<font color='red' size='5'>" + str + "</font>";; } function SayHello(){ varusr=window.document.f1.username.value; varrnd = Math.random(); varurl="sayhello.php?id="+rnd +"&usr="+usr; postRequest(url); } </script> </head>

  33. <body> <h1 align="center"><font color="#000080">Simple Ajax Example</font></h1> <p align="center"><font color="#000080">Enter your name and then press "Say Hello Button"</font></p> <form name="f1"> <p align="center"><font color="#000080">&nbsp; Enter your name: <input type="text" name="username" id="username"> <input value="Say Hello" type="button" onclick='JavaScript:SayHello()' name="showdate"></font></p> <div id="result" align="center"></div> </form> <div id=result></div> </body> </html>

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

  35. sample.html <html>    <head><title>welcome</title>    <script language="javascript">reqObj=null;        function varify(){document.getElementById("res").innerHTML="Checking";            if(window.XMLHttpRequest){reqObj=new XMLHttpRequest();            }else {reqObj=new ActiveXObject("Microsoft.XMLHTTP");            }reqObj.onreadystatechange=process;reqObj.open("POST","./a.jsp?id="+document.getElementById("username").value,true);reqObj.send(null);        }        function process(){            if(reqObj.readyState==4){document.getElementById("res").innerHTML=reqObj.responseText;            }        }        </script>    </head>    <body>        <h1>welcome to this application</h1>    <form method="get" action="first">        User Name<input type="text" name="t1" id="username" onblur="varify();"><span id="res"></span><br/>        Password<input type="text" name="t2"><br/>        <input type ="submit" value="Press"/>    </form>    </body></html>

  36. a.jsp • <%String user=request.getParameter("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><%}%>

  37. Advantages of AJAX • XMLHttpRequest - 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.

  38. Dis Adv. • XMLHttpRequest -In the older version of IE (5 & 6) ActiveX 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 URL-encoded.

More Related