25250716 seminar-on-ajax text


Published on


Published in: Education
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

25250716 seminar-on-ajax text

  1. 1. Introduction What is Ajax? History Why use Ajax? Ajax as a combination ofTechnologies How Ajax works? Advantages Drawbacks Future Conclusion References
  2. 2. INTRODUCTION:Internet is very important technology in this era. Most of students, teachersand computer users are using this technology. However, there are some problemswith this technology. Because of interacting with some servers across the world,this procedure makes the interacting not that fast. Web-designers and Internetdevelopers try to solve this problem by many ways. One of these ways is designnew web-programming languages such as JavaScript or XML. Unfortunately, thesenew ways solve a part of these problems but the other parts still face problems.Some scientists say that if there is an ideal solvent to this problem, thepeople life will depend almost completely on the computers. Here we are going totell you about a new technology called Ajax that has been solving big part ofproblems with browsing the Internet. Ajax is actually a family of technologiesthat have been available for years. The means to make requests to the serverusing only JavaScript were built into Internet Explorer 5.5, but thepossibilities of the technology were overlooked. It was only in 2005 that thetechniques were rediscovered and used, notably to excellent effect in Google sGmail web application.WHAT IS AJAX?AJAX (shorthand for Asynchronous JavaScript and XML): Asynchronous: This meansthat when you send a request, you wait for the response to come back, but arefree to do other things while you wait. The response probably won t come backimmediately, so you set up a function that will wait for the response to be sentback by the server, and react to it once that happens. JavaScript: JavaScript isused to make a request to the server. Once the response is returned by theserver, you will generally use some more JavaScript to modify the currentpage s document object model in some way to show the user that the submissionwent through successfully.
  3. 3. XML: The data that you receive back from the server will often be packaged up asa snippet of XML, so that it can be easily processed with JavaScript. This datacan be anything you want, and as long as you want. Ajax is a group ofinterrelated web development techniques used on the client-side to createinteractive web applications or rich Internet applications. With Ajax, webapplications can retrieve data from the server asynchronously in the backgroundwithout interfering with the display and behavior of the existing page. The useof Ajax has led to an increase in interactive or dynamic interfaces on web pagesand better quality of Web services due to the asynchronous mode. Data is usuallyretrieved using the XMLHttpRequest object. Despite the name, the use ofJavaScript and XML is not actually required, nor do the requests need to beasynchronous.HISTORY:Techniques for the asynchronous loading of content date back to the mid 1990s.Java applets were introduced in the first version of the Java language in 1995.These allow compiled clientside code to load data asynchronously from the webserver after a web page is loaded. In 1996, Internet Explorer introduced theIFrame element to HTML, which also enables this to be achieved. In 1999,Microsoft created the XMLHTTP ActiveX control in Internet Explorer 5, which isnow supported by Mozilla, Safari and other browsers as the native XMLHttpRequestobject. However, this feature only became widely known after being used by Gmail(2004) and Google Maps (2005). Ajax is only a name given to a set of tools thatpreviously existed. The main part is XMLHttpRequest, a server-side object usablein JavaScript that was implemented into Internet Explorer since the 4.0 version.In Internet Explorer it is an ActiveX object that was first named XMLHTTPsometimes, before to be generalized on all browsers under the nameXMLHttpRequest, when the Ajax technology becomes commonly used. The use ofXMLHttpRequest in 2005 by Google, in Gmail and Google Maps has contributed tothe success of this format. But this is the when the name Ajax was itself coinedthat the technology started to be so popular.
  4. 4. WHY USE AJAX?Mainly AJAX is used to build a fast, dynamic website, and also to saveresources. For improving sharing of resources, it is better to use the power ofall the client computers rather than just a unique server and network. Ajaxallows performing processing on client computer (in JavaScript) with data takenfrom the server. The processing of web page formerly was only server-side, usingweb services or PHP scripts, before the whole page was sent within the network.But Ajax can selectively modify a part of a page displayed by the browser, andupdate it without the need to reload the whole document with all images, menus,etc. For example, fields of forms, choices of user, may be processed and theresult displayed immediately into the same page.AJAX AS A COMBINATION OF TECHNOLOGIESThe term Ajax has come to represent a broad group of web technologies that canbe used to implement a web application that communicates with a server in thebackground, without interfering with the current state of the page: HTML and CSSfor presenting. JavaScript for local processing, and DOM (Document Object Model)to access data inside the page or to access elements of XML file read on theserver The XMLHttpRequest object is used to read or send data on the serverasynchronously. Optionally: DOM Parser may be used. PHP or another scriptinglanguage may be used on the server. XML and XSLT to process the data if returnedin XML form.
  5. 5. HOW AJAX WORKS?Ajax uses a programming model with display and events. These events are useractions; they call functions associated to elements of the web page.Interactivity is achieved with forms and buttons. DOM allows to link elements ofthe page with actions and also to extract data from XML files provided by theserver. To get data on the server, XMLHttpRequest provides two methods: - open:create a connection. - send: send a request to the server. Data furnished by theserver will be found in the attributes of the XMLHttpRequest object: -responseXml for an XML file or - responseText for a plain text. Take note that anew XMLHttpRequest object has to be created for each new file to load. We haveto wait for the data to be available to process it, and in this purpose, thestate of availability of data is given by the readyState attribute ofXMLHttpRequest.States of readyState follow (only the last one is really useful):0: not initialized. 1: connection established. 2: request received. 3: answer inprocess. 4: finished.Before discussing how Ajax works, you should know how the old technologies work.Why should you know how the old technologies work? The answer is simply toobserve the difference between the old technologies and Ajax. The action is sentto the server by requesting an HTTP trigger and you, the internet user, wait tothe server to respond. It is also not that simple. The server will do many jobsin each request. After doing some processing stuff the server will respond tothe client (see figure1). (2:1)
  6. 6. This way is very technical but do you ask yourself this question: What you willdo when the server does its jobs? The answer is nothing but waiting for the jobsto be done by the server. This is clearly a problem. It is wasting time andmoney. (2:2) On the other hand, Ajax will eliminate the number of interactionswith the server by asking the server to do some specific job(s). How Ajax doesthat? This is done by putting Ajax Engine in the middle between the client andthe server. Ajax engine will make the application is less responsive. (2:2)Furthermore, after knowing that there is something called Ajax engine but youwhere it is or how to get it. Do not worry, the user does not have to downloadthis engine or buy it. It is simply when the user tries to load the webpage, theAjax engine will be loaded instead. This engine is written in JavaScript.Rendering the visual interface and interaction with the server is not a user sresponsibilities it is an Ajax engine s responsibilities. This whole processestake place asynchronously. It is independent of communication with the server.So, if you want to re-load or update the webpage, then you do not have to startfrom an empty webpage. So, the internet s user will interact with Ajax engineinstead of interacting with the server. How Ajax engine working is not ourissue. So as I said earlier, Ajax engine will take care of interacting withserver asynchronously.The XMLHttpRequest objectAllows interacting with the servers, thanks to its methods and attributes.AttributesreadyState status responseText responseXml onreadystatechange The codesuccessively changes value from 0 to 4 that means for "ready". 200 is OK 404 ifthe page is not found. Holds loaded data as a string of characters. Holds an XMLloaded file, DOMs method allows to extract data. Property that takes a functionas value that is invoked when the readystatechange event is dispatched.
  7. 7. Methodsmode: type of request, GET or POST open(mode, url, boolean) url: the location ofthe file, with a path. boolean: true (asynchronous) / false (synchronous).Optionally, a login and a password may be added to arguments. send("string")Null for a GET command.Building a request, step by stepFirst step: create an instance This is just a classical instance of class, buttwo options must be tried, for browser compatibility. if (window.XMLHttpRequest){ xhr = new XMLHttpRequest(); } else if (window.ActiveXObject) // ActiveXversion { xhr = new ActiveXObject("Microsoft.XMLHTTP"); // Internet Explorer }Or exceptions may be used instead: try { xhr = newActiveXObject("Microsoft.XMLHTTP"); } catch(e) { xhr = newXMLHttpRequest(); } // Other browsers. // Failed // Trying Internet Explorer //Firefox, Safari, ... // Object of the current windows
  8. 8. Second step: wait for the response The response and further processing areincluded in a function and the return of the function will be assigned to theonreadystatechange attribute of the object previously created.xhr.onreadystatechange = function() { // instructions to process the response };if (xhr.readyState == 4) { // Received, OK } else { // Wait... }Third step: make the request itself Two methods of XMLHttpRequest are used: -open: command GET or POST, URL of the document, true for asynchronous. - send:with POST only, the data to send to the server. The request below read adocument on the server. xhr.open(GET, http://www.xul.fr/somefile.xml, true);xhr.send(null);
  9. 9. ExamplesGet a text<html> <head> <script> function submitForm() { var xhr; try { xhr = newActiveXObject(Msxml2.XMLHTTP); } catch (e) { try { xhr = newActiveXObject(Microsoft.XMLHTTP); catch (e2) { try { xhr = newXMLHttpRequest(); catch (e3) { xhr = false; } } } } }xhr.onreadystatechange = function() { if(xhr.readyState == 4) { if(xhr.status ==200) document.ajax.dyn="Received:" + xhr.responseText; elsedocument.ajax.dyn="Error code " + xhr.status; } };
  10. 10. xhr.open(GET, "data.txt", true); xhr.send(null); } </script> </head><body> <FORM method="POST" name="ajax" action=""> <INPUT type="BUTTON"value="Submit" ONCLICK="submitForm()"> <INPUT type="text" name="dyn" value=""></FORM> </body> </html>Syntax of form using AjaxComments on the code:new ActiveXObject(Microsoft.XMLHTTP) This constructor is for Internet Explorer.new XMLHttpRequest() This constructor is for any other browser includingFirefox.http.onreadystatechange An anonymous function is assigned to the eventindicator.http.readyState == 4 The 4 state means for the response is ready and sent by theserver.http.status == 200 This status means ok, otherwise some error code is returned,404 for example.
  11. 11. http.open( POST", "data.xml", true); POST or GET URL of the script to execute.True for asynchronous (false for synchronous).http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); Thisis for POST only. http.send(document.getElementById("TYPEDTEXT").value); Senddata to the server. Data comes from the "TYPEDTEXT" variable filled through theform by the user.Get from XMLTo get data from an XML file, we have just to replace this line:document.ajax.dyn="Received:" + xhr.responseText; By this code: var doc =xhr.responseXML; // Assign the XML file to a var var element =doc.getElementsByTagName(root).item(0); // Read the first elementdocument.ajax.dyn.value= element.firstChild.data; // Assign the content to theformWrite to bodyIn this demo, the text read is put into the body of the page, and not into atextfield. The code below replaces the textfield form object and the second partreplaces the assignment into the JavaScript function. <div id="zone"> ... sometext to replace ... </div> document.getElementById("zone").innerHTML ="Received:" + xhr.responseText;
  12. 12. Post a textIn this demo, a text is sent to the server and is written into a file. The callto the "open" method changes, the argument is POST, the url is the name of afile or script that receives the data sent, and that must process it. And the"send" method has now a value as argument that is a string of parameters.xhr.open ("POST", "ajax-post-text.php", true); xhr.setRequestHeader ("Content-Type", "application/x-www-form-urlencoded"); xhr.send (data); The parameter ofthe send method is in the format of the HTML POST method. When several valuesare sent, they are separated by the ampersand symbol: var data = "file=" + url +"&content=" + content;The "file" parameter is the name of a file created to store the content. Thefilename must be checked by the server to prevent any other file to be modified.Using an external fileIt is simpler to include a JavaScript file. This line will be included into thehead section of the HTML page: <script src="ajax.js"type="text/javascript"></script>And the function is called with this statement: var xhr = createXHR();View the script in the ajax.js file.
  13. 13. Old technologies Comparison with AJAX.Figure. 1(a)
  14. 14. ADVANTAGES:Bandwidth utilization: In many cases, related pages on a website consist of muchcontent that is common between them. Using traditional methods, that contentwould have to be reloaded on every request. However, using Ajax, a webapplication can request only the content that needs to be updated, thusdrastically reducing bandwidth usage and load time. User interface: The use ofasynchronous requests allows the clients Web browser UI to be more interactiveand to respond quickly to inputs, and sections of pages can also be reloadedindividually. Users may perceive the application to be faster or moreresponsive, even if the application has not changed on the server side. Moreefficient: The use of Ajax can reduce connections to the server, since scriptsand style sheets only have to be requested once. State can be maintainedthroughout a Web site. JavaScript variables will persist because the maincontainer page need not be reloaded.DRAWBACKS:The ease of use of Ajax-powered interfaces often dramatically increases thenumber of user-generated requests to web servers and their back-ends (databases,or other). This can lead to slower response times and additional hardware needsto support Ajax-powered interfaces. Pages dynamically created using successiveAjax requests do not automatically register themselves with the browsershistory engine, so clicking the browsers "back" button may not return the userto an earlier state of the Ajax-enabled page, but may instead return them to thelast full page visited before it.
  15. 15. Because most web crawlers do not execute JavaScript code, publicly indexable webapplications should provide an alternative means of accessing the content thatwould normally be retrieved with Ajax, to allow search engines to index it. Anyuser whose browser does not support Ajax or JavaScript, or simply has JavaScriptdisabled, will not be able to use its functionality. Similarly, devices such asmobile phones, PDAs, and screen readers may not have support for JavaScript orthe XMLHttpRequest object. If JavaScript is not activated, Ajax cant works. Theuser must be asked to set JavaScript from within options of the browser, withthe "noscript" tag. Since data to display are loaded dynamically, they are notpart of the page, and the keywords inside are not viewed by search engines. Theasynchronous mode may change the page with delays (when the processing on theserver takes some times), this may be disturbing. The back button may bedeactivated. This may be overcome.FUTURE:Big applications of Ajax showed that it is not just a technical issues but it isa real world application. As the seminar demonstrates earlier, Ajax has theability to grow. Ajax applications face some non-technical difficulties. Forinstance, the programmers and the developers are not qualified yet to implementthis approach. However, big companies like Microsoft, Sun Microsystems Inc andTIBCO Software Inc want to use Ajax in their applications (4:1). This step willmake Ajax is very popular. Microsoft wants to develop smart client strategy byimplementing Ajax (9:2). Microsoft Atlas is an Ajax based programming framework(8:1).
  16. 16. CONCLUSION:Internet-applications have many benefits over desktop applications; they canreach a larger audience, they are easier to install and support, and easier todevelop. However, Internetapplications are not always as "rich" and user-friendly as traditional desktop applications. AJAX applications are browser-independent and platform-independent. With AJAX, Internet applications can bemade richer and more user-friendly. AJAX is not a new programming language, buta new technique for creating better, faster, and more interactive webapplications. AJAX uses asynchronous data transfer (HTTP requests) between thebrowser and the web server, allowing web pages to request small bits ofinformation from the server instead of whole pages. New applications use Ajaxwill be very popular.REFRENCES:www.google.com www.w3schools.com www.wikipedia.com www.yourhtmlsource.comwww.whatis.com