Document Details

Uploaded by Deleted User

Tags

ajax programming asynchronous javascript xml http request web development

Summary

This document covers Ajax, a web development technique that uses asynchronous JavaScript and XML (or JSON) to update parts of a web page dynamically without requiring a full page refresh. It also discusses some characteristics of Ajax applications and compares them to traditional web applications.

Full Transcript

Ajax Asynchronous JavaScript + XML Mark Andreessen, Netscape, 1995: "MS Windows will be reduced to a poorly debugged set of device drivers running under Netscape Navigator, with desktop-style applications runn...

Ajax Asynchronous JavaScript + XML Mark Andreessen, Netscape, 1995: "MS Windows will be reduced to a poorly debugged set of device drivers running under Netscape Navigator, with desktop-style applications running inside the browser". This did not happen until 10 years later (true/false?) This content is protected and may not be shared, uploaded, or distributed. © 2007-2024 Marco Papa & Ellis Horowitz 1 What are we Talking about today? Core Technologies of Ajax – JavaScript and DOM Manipulation – XMLHttpRequest (XHR) and Fetch – JSON as a Data Format Asynchronous Communication – No Full-Page Refresh – Asynchronous Server Requests – Client-side Processing Ajax Application Characteristics – Smooth User Interaction – Interactive Elements – Web Mashups Copyright © Ellis Horowitz 1998-2024 2 Asynchronous JavaScript + XML Ajax isn’t a technology. It’s really several technologies. Ajax incorporates: – standards-based presentation using XHTML; – CSS, dynamically manipulated using JavaScript; – dynamic display and interaction using the Document Object Model (DOM). Web page exposed as DOM object; – data interchange using XML (nowadays JSON); – asynchronous data retrieval using XMLHttpRequest, a JavaScript object, a.k.a “Web remoting”; – JavaScript binding everything together; – Server no longer performs display logic, only business logic. Acronym originated by Jesse James Garrett in 2005: https://immagic.com/eLibrary/ARCHIVES/GENERAL/ADTVPATH /A050218G.pdf © 2007-2024 Marco Papa & Ellis Horowitz 3 Some History and Browsers Supporting Ajax The XMLHttpRequest object (XHR) is the main element of Ajax programming. Microsoft first implemented the XMLHttpRequest object in Internet Explorer 5 (IE5) for Windows as an ActiveX object in March 1999, making it the first Ajax-enabled browser. Similar functionality is covered in a recommended W3C standard, Document Object Model (DOM) Level 3 Load and Save Specification (April 2004): http://www.w3.org/TR/DOM-Level-3-LS Engineers on the Mozilla project implemented a compatible native version for Mozilla 1.0 (included in Netscape 7, Firefox 1.0 and later releases). Apple has done the same starting with Safari 1.2. Other browsers supporting XMLHttpRequest include: – Opera 7.6+, Apple Safari 1.2+, all mobile browsers XMLHttpRequest moved to W3C in 2006 and back to WHATWG in 2012 as XMLHttpRequest Living Standard: – https://xhr.spec.whatwg.org/ © 2007-2024 Marco Papa & Ellis Horowitz 4 An Example Using Ajax - Google Maps Initial screen zoom 3 times drag map and zoom See: https://maps.google.com Notice that the page is never explicitly refreshed. View source and search for XMLHttpRequest; you will find multiple occurrences. (found 2 times on maps.google.com) © 2007-2024 Marco Papa & Ellis Horowitz 5 A Mash-Up Combines Multiple Sources of Data A “mash-up” is a web application that consumes ("remixes") content from different sources and aggregates them to create a new application Mashup Example – www.zillow.com A combination of satellite photos with records of home sale prices placed on top of the appropriate houses Found 4+ references of XMLHttpRequest © 2007-2024 Marco Papa & Ellis Horowitz 6 Characteristics of Ajax Applications They are applications (or Apps), not just web sites They allow for smooth, continuous interaction "Live" content Visual Effects Animations, dynamic icons Single keystrokes can lead to server calls New Widgets (selectors, buttons, tabs, lists) New Styles of Interaction (drag-and-drop, keyboard shortcuts, double-click) © 2007-2024 Marco Papa & Ellis Horowitz 7 Comparing Traditional vs. AJAX Websites Traditional Ajax Interface construction is Interface is manipulated mainly the responsibility by client-side JavaScript of the server manipulations of the User interaction is via Document Object Model form submissions (DOM) An entire page is required User interaction via HTTP for each interaction requests occur ‘behind the (bandwidth) scenes’ Application is unavailable Communication can be while an interaction is restricted to data only processing (application Application is always speed) responsive © 2007-2024 Marco Papa & Ellis Horowitz 8 How to Recognize an Ajax Application Internally “View Source” in the browser and search for: Javascript code that invokes: – XMLHttpRequest or fetch JavaScript that “loads” other JavaScript code (files with.js extension) XML code passed as text strings to a server, such as ‘…’ Javascript sections that embed code between // IFRAMES / JavaScript code that creates IFRAMEs, such as window.document.createElement("iframe") Use browser “developer tools” to find the code jQuery Ajax functions (as jQuery.ajax()) fetch() © 2007-2024 Marco Papa & Ellis Horowitz 9 The Classic Web Application Model Most user actions in the browser interface trigger an HTTP request back to a web server. The server does some processing — retrieving data, crunching numbers, talking to various legacy systems. The server then returns an HTML page to the client. Approach issues: – It doesn’t make for a great user experience. – While the server is doing its thing, the user is waiting. – And at every step in a task, the user waits some more. © 2007-2024 Marco Papa & Ellis Horowitz 10 The Ajax Web Application Model Ajax introduces an intermediary — an Ajax engine — between the user and the server. Instead of loading a webpage, at the start of the session, the browser loads an Ajax engine — written in JavaScript and usually stored in a hidden frame. This engine is responsible for – rendering the interface that the user sees – communicating with the server on the user’s behalf. The Ajax engine allows the user’s interaction with the application to happen asynchronously — independent of communication with the server. Approach Benefits: – An Ajax application eliminates the start-stop- start-stop nature of interaction on the Web. – The user is never staring at a browser window with hourglass, waiting for the server to do something. – The application is more responsive. © 2007-2024 Marco Papa & Ellis Horowitz 11 AJAX: Cuts down on user wait time Uses client to offload some work from the server Asynchronous operation © 2007-2024 Marco Papa & Ellis Horowitz 12 Traditional Web Applications Model compared to the Ajax Model © 2007-2024 Marco Papa & Ellis Horowitz 13 Classic Web Application Model (synchronous) From Jesse James Garrett’s “Ajax: a New Approach to Web Applications”. See: http://adaptivepath.org/ideas/ajax-new-approach-web-applications/ (archived below) https://immagic.com/eLibrary/ARCHIVES/GENERAL/ADTVPATH/A050218G.pdf © 2007-2024 Marco Papa & Ellis Horowitz 14 Ajax Web Application Model (asynchronous) © 2007-2024 Marco Papa & Ellis Horowitz 15 Ajax Engine Role Every user action that normally would generate an HTTP request takes the form of a JavaScript call to the Ajax engine instead. Any response to a user action that doesn't require a trip back to the server, such as: – simple data validation – editing data in memory – even some navigation the engine handles on its own. If the engine needs something from the server in order to respond, such as: – submitting data for processing – loading additional interface code – retrieving new data the engine makes those requests asynchronously, retrieving results in JSON or XML, without stalling a user’s interaction with the application. © 2007-2024 Marco Papa & Ellis Horowitz 16 Initiating the XMLHttpRequest Object Creating an instance of the XMLHttpRequest object requires branching syntax to account for browser differences. For all modern browsers a simple call to the object's constructor function does the job: var req = new XMLHttpRequest(); The object reference returned by both constructors is to an abstract object that works entirely out of view of the user. Its methods control all operations, while its properties hold, among other things, various data pieces returned from the server. © 2007-2024 Marco Papa & Ellis Horowitz 17 XMLHttpRequest Object Methods See latest requests and responses at: https://xhr.spec.whatwg.org/#request © 2007-2024 Marco Papa & Ellis Horowitz 18 XMLHttpRequest Object Methods (cont’d) Of the methods shown in the Table on the previous slide, the open() and send() methods are the ones you'll likely use most. open() sets the scene for an upcoming operation. Two required parameters are the HTTP method you intend for the request and the URL for the connection. For the method parameter, use "GET" on operations that are primarily data retrieval requests; use "POST" on operations that send data to the server, especially if the length of the outgoing data is potentially greater than 512 bytes. The URL may be either a complete or relative URL. It is safer to send asynchronously and design your code around the onreadystatechange event for the request object. send initiates the transaction. © 2007-2024 Marco Papa & Ellis Horowitz 19 XMLHttpRequest Object Properties See latest at: https://xhr.spec.whatwg.org/#xmlhttprequest-response © 2007-2024 Marco Papa & Ellis Horowitz 20 XMLHttpRequest Object Properties (cont’d) Use the readyState property inside the event handler function that processes request object state change events. While the object may undergo interim state changes during its creation and processing, the value that signals the completion of the transaction is 4. Access data returned from the server via the responseText or responseXML properties. The former provides a string representation of the data, which is used today for JSON data. More powerful, however, is the XML document object in the responseXML property. This object is a full-fledged document node object, which can be examined and parsed using W3C DOM node tree methods and properties. Note, however, that this is an XML, rather than HTML, document, meaning that you cannot count on the DOM's HTML module methods and properties. In today’s implementations, everybody is using responseText, as this is the way to get JSON data. The XMLHttpRequest Living Standard includes a responseType attribute, that can be set to arraybuffer, blob, document, json and text, and a response property that returns a “parsed json object” when json is selected. © 2007-2024 Marco Papa & Ellis Horowitz 21 XMLHttpRequest Example Code This code instantiates an XmlHttpRequest object depending upon the browser © 2007-2024 Marco Papa & Ellis Horowitz 22 onreadystatechange Event Handler Function function processReqChange() { // see previous slide // only if req shows "loaded" if (req.readyState == 4) { // only if "OK" if (req.status == 200) { // processing statements req.responseText // for JSON // and req.responseXML for XML go here... } else { alert("There was a problem retrieving the data:\n" + req.statusText); } } } © 2007-2024 Marco Papa & Ellis Horowitz 23 Security Issues When the XMLHttpRequest object operates within a browser, it adopts the same-domain security policies of typical JavaScript activity (sharing the same "sandbox," as it were). First, on most browsers supporting this functionality, the page that bears scripts accessing the object needs to be retrieved via http: protocol, meaning that you won't be able to test the pages from a local hard disk (file: protocol) without some extra security issues cropping up, especially in Mozilla and IE on Windows. Second, the domain of the URL request destination must be the same as the one that serves up the page containing the script. This means, unfortunately, that client-side scripts cannot fetch web service data from other sources and blend that data into a page. Everything must come from the same domain. © 2007-2024 Marco Papa & Ellis Horowitz 24 AJAX Cross Domain Security www.other.com www.other.com www.myco.com www.myco.com browser browser www.myco.com The one exception is for images: images can come from any domain, without any security risk. This is why all the mash-up applications involve images For security reasons, scripts are only allowed to access data which They simply would not be possible for other kinds comes from the same domain of data © 2007-2024 Marco Papa & Ellis Horowitz 25 Cross-domain Restrictions and a Solution Browser security restrictions prevent your web application from opening network connections to domains other than the one your application came from. For example, suppose your web application wants to use data both from your site and from Yahoo!; normally this is not possible as it is a violation of browser cross-domain security policy. One way to work around this issue is to install a web proxy on your server that will pass requests from your application to Yahoo! and the data back again. This is what is used in our assignments. If you are using a proxy to relay requests from your web application to Yahoo!, the actual request URL you use from your web application is different, as you must relay your request through your web server proxy. Another way is CORS, which works on all recent browsers. Of course, you will need a server that you trust and that is set up to accept CORS requests. (see slides later in this set) © 2007-2024 Marco Papa & Ellis Horowitz 26 Why You Need a Proxy © 2007-2024 Marco Papa & Ellis Horowitz 27 Alternative: Fetch API The Fetch API provides a JavaScript interface for accessing and manipulating requests and responses. It also provides a global fetch() method to fetch resources asynchronously. Fetch also provides a single logical place to define other HTTP-related concepts such as CORS and HTTP extensions. The fetch specification differs from jQuery.ajax() in three main ways: – The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. – fetch() won't receive cross-site cookies; you can’t establish a cross site session using fetch. Set-Cookie headers from other sites are silently ignored. – Fetch() won’t send cookies, unless you set the credentials init option. won't receive cross-site cookies; © 2007-2024 Marco Papa & Ellis Horowitz 28 Alternative: Fetch API (cont’d) see: https://developer.mozilla.org/en- US/docs/Web/API/Fetch_API/Using_Fetch The fetch() method can optionally accept a second parameter, an init object that allows you to control a few settings: © 2007-2024 Marco Papa & Ellis Horowitz 29 A First Ajax Example – Using Ajax to Download Files The javascript file does all of the work First Ajax Script

Use Quizgecko on...
Browser
Browser