AJAX Programming Chris Seddon

Similar documents
Introduction to Ajax. Sang Shin Java Technology Architect Sun Microsystems, Inc.

Module7: AJAX. Click, wait, and refresh user interaction. Synchronous request/response communication model. Page-driven: Workflow is based on pages

Fall Semester (081) Module7: AJAX

Session 11. Ajax. Reading & Reference

AJAX Basics. Welcome to AJAX Basics presentation. My name is Sang Shin. I am Java technology architect and evangelist from Sun Microsystems.

2/6/2012. Rich Internet Applications. What is Ajax? Defining AJAX. Asynchronous JavaScript and XML Term coined in 2005 by Jesse James Garrett

Introduction to Ajax

Session 18. jquery - Ajax. Reference. Tutorials. jquery Methods. Session 18 jquery and Ajax 10/31/ Robert Kelly,

Programming for Digital Media. Lecture 7 JavaScript By: A. Mousavi and P. Broomhead SERG, School of Engineering Design, Brunel University, UK

jmaki Overview Sang Shin Java Technology Architect Sun Microsystems, Inc.



It is highly recommended that you are familiar with HTML and JavaScript before attempting this tutorial.

AJAX: Introduction CISC 282 November 27, 2018

A synchronous J avascript A nd X ml

10.1 Overview of Ajax

Session 11. Calling Servlets from Ajax. Lecture Objectives. Understand servlet response formats

Developing Ajax Web Apps with GWT. Session I

Portlets and Ajax: Building More Dynamic Web Apps

CITS1231 Web Technologies. Ajax and Web 2.0 Turning clunky website into interactive mashups

Web Programming Step by Step

XMLHttpRequest. CS144: Web Applications

TIME SCHEDULE MODULE TOPICS PERIODS. HTML Document Object Model (DOM) and javascript Object Notation (JSON)

Asynchronous JavaScript + XML (Ajax)

An Introduction to AJAX. By : I. Moamin Abughazaleh

AJAX ASYNCHRONOUS JAVASCRIPT AND XML. Laura Farinetti - DAUIN

CSC309: Introduction to Web Programming. Lecture 11

Web Programming. Lecture 11. University of Toronto

Ajax or AJAX? The acronym AJAX has changed to the term Ajax, which does not represent specific technologies

,

Credits: Some of the slides are based on material adapted from

Contents. Demos folder: Demos\14-Ajax. 1. Overview of Ajax. 2. Using Ajax directly. 3. jquery and Ajax. 4. Consuming RESTful services

AJAX: The Basics CISC 282 March 25, 2014

Introduction to AJAX Bringing Interactivity & Intuitiveness Into Web Applications. By : Bhanwar Gupta SD-Team-Member Jsoft Solutions

Module 5 JavaScript, AJAX, and jquery. Module 5. Module 5 Contains 2 components

A.A. 2008/09. What is Ajax?

AJAX. Introduction. AJAX: Asynchronous JavaScript and XML

JavaServer Faces Technology, AJAX, and Portlets: It s Easy if You Know How!

AJAX: The Basics CISC 282 November 22, 2017

Ajax. Ronald J. Glotzbach

Introduction Haim Michael. All Rights Reserved.

AJAX: Rich Internet Applications

Term Paper. P r o f. D r. E d u a r d H e i n d l. H o c h s c h u l e F u r t w a n g e n U n i v e r s i t y. P r e s e n t e d T o :

User Interaction: jquery

AJAX. Lab. de Bases de Dados e Aplicações Web MIEIC, FEUP 2010/11. Sérgio Nunes

Tooling for Ajax-Based Development. Craig R. McClanahan Senior Staff Engineer Sun Microsystems, Inc.

Ajax in Oracle JDeveloper

Etanova Enterprise Solutions

Module 5 JavaScript, AJAX, and jquery. Module 5. Module 5 Contains an Individual and Group component

Course Details. Skills Gained. Who Can Benefit. Prerequisites. View Online URL:

Web application Architecture

AJAX(Asynchronous Javascript + XML) Creating client-side dynamic Web pages

Copyright Descriptor Systems, Course materials may not be reproduced in whole or in part without prior written consent of Joel Barnum

1 Introduction. 2 Web Architecture

Create-A-Page Design Documentation

Ajax- XMLHttpResponse. Returns a value such as ArrayBuffer, Blob, Document, JavaScript object, or a DOMString, based on the value of

! The final is at 10:30 am, Sat 6/4, in this room. ! Open book, open notes. ! No electronic devices. ! No food. ! Assignment 7 due 10pm tomorrow

CS 5142 Scripting Languages

Abstract. 1. Introduction. 2. AJAX overview

AJAX and PHP AJAX. Christian Wenz,

The course also includes an overview of some of the most popular frameworks that you will most likely encounter in your real work environments.

Controller/server communication

Ajax and Web 2.0 Related Frameworks and Toolkits. Dennis Chen Director of Product Engineering / Potix Corporation

Using Development Tools to Examine Webpages

Working with Javascript Building Responsive Library apps

Web 2.0, AJAX and RIAs

State of the Open Web. Brad Neuberg, Google

Lesson 12: JavaScript and AJAX

Outline. Introduction to JavaScript Resources What is JavaScript? JavaScript in web pages

REST AND AJAX. Introduction. Module 13

UI Course HTML: (Html, CSS, JavaScript, JQuery, Bootstrap, AngularJS) Introduction. The World Wide Web (WWW) and history of HTML

Rich Web Applications in Server-side Java without. Plug-ins or JavaScript

Web Application Security

Developing Future Web Application with AJAX and ASP.NET Project "Atlas"

JavaScript Specialist v2.0 Exam 1D0-735

Writing with YUI. Doug Bell Developer / Janitor

Controller/server communication

JavaScript Programming

AJAX in Apache MyFaces A New Approach To Web Applications

Web 2.0 and Security

FUSE Ajax Tutorial. 07/06 Version 1.2

E ECMAScript, 21 elements collection, HTML, 30 31, 31. Index 161

RIA Security - Broken By Design. Joonas Lehtinen IT Mill - CEO

Web 2.0 Käyttöliittymätekniikat

Paul Withers Intec Systems Ltd By Kind Permission of Matt White and Tim Clark

Say goodbye to the pains of Ajax. Yibo

Jquery.ajax Call Returns Status Code Of 200 But Fires Jquery Error

Events & Callbacks (ESaaS 6.5)! 2013 Armando Fox & David Patterson, all rights reserved

eclipse rich ajax platform (rap)

Oracle WebLogic Portal

Code Examples Using Java ME Technology and New Web 2.0 Services (Beyond Google Maps)

GRITS AJAX & GWT. Trey Roby. GRITS 5/14/09 Roby - 1

COURSE OUTLINE MOC 20480: PROGRAMMING IN HTML5 WITH JAVASCRIPT AND CSS3

CSC 443: Web Programming

welcome to BOILERCAMP HOW TO WEB DEV

Ajax HTML5 Cookies. Sessions 1A and 1B

Rich Web Applications in Server-side Java without. Plug-ins or JavaScript

JavaScript CoAPRequest API

Homework 8: Ajax, JSON and Responsive Design Travel and Entertainment Search (Bootstrap/Angular/AJAX/JSON/jQuery /Cloud Exercise)

Jquery Manually Set Checkbox Checked Or Not

Transcription:

AJAX Programming Chris Seddon seddon-software@keme.co.uk 2000-12 CRS Enterprises Ltd 1

2000-12 CRS Enterprises Ltd 2

What is Ajax? "Asynchronous JavaScript and XML" Originally described in 2005 by Jesse James Garrett of Adaptive Path Essentially distills existing technologies Asynchronous communication between client and server Partial screen updates Replaces traditional click-wait-redraw model Faster responses Remaining page context available during refresh Updates can be triggered on different events No longer necessary to click on link or button 2000-12 CRS Enterprises Ltd 3

Key Ajax Technologies AJAX is not itself a language! Uses JavaScript on the client and any Language on the Server Client Technologies used: HTML (or (or XHTML) and CSS Presenting Presenting information information Document Object Model Dynamic Dynamic display display and and interaction interaction with with the the information information XMLHttpRequest object Retrieving Retrieving data data ASYNCHRONOUSLY from from the the web web server. server. Javascript Binding Binding everything everything together together 2000-12 CRS Enterprises Ltd 4

Who is using AJAX? Who Isn't? AJAX is now widespread BBC Home page using portals Google Office Applications Creation of thick client look and feel Google Maps Background fetch of map data Flickr Background fetch of photos for display 2000-12 CRS Enterprises Ltd 5

Portals Portals are often built using portlet components Parts of other web sites Users can select from available portlets... and customize their layouts. Multiple views of the same Web application Consider del.icio.us: Browser, JSON, REST/XML, JavaScript Widget interfaces all to the same application. You don t have to go to http://del.icio.us to use it. Simple programming interfaces encourage do it yourself mash-ups JSON, AJAX compatible REST APIs 2000-12 CRS Enterprises Ltd 6

The Ajax Web Application Model Without Ajax User Interface HTTP(S) HTML + CSS Web Server Data Store, Backend processing JavaScript With Ajax User Interface HTML + CSS Ajax Engine HTTP(S) XML / text data Web Server Data Store, Backend processing 2000-12 CRS Enterprises Ltd 7

The Ajax Web Application Model - 2 Client Server data data data data time Client Browser UI input display Ajax Engine Server data data data data time 2000-12 CRS Enterprises Ltd 8

Steps in an Ajax Interaction <script> 2 </script> 1 XMLHttpRequest XMLHttpRequest chris 6 function function callback() callback() {{ // // Update Update HTML HTML DOM DOM // // with with result result }} onkeyup event submit NOT clicked Submit Submit 3 validate?id=chris 5 <response>... </ response > Server-side processing (not (not AJAX AJAX aware) aware) 4 Database 2000-12 CRS Enterprises Ltd 9

Introducing XMLHttpRequest XMLHttpRequest JavaScript object encapsulates making HTTP request from browser to server Scripting HTTP with XMLHttpRequest is a three-part process: 1. 1. Creating an an XMLHttpRequest object 2. 2. Submitting your HTTP request to to a web server 3. 3. Synchronously or or asynchronously retrieving the server s response 2000-12 CRS Enterprises Ltd 10

XMLHttpRequest Methods Methods open(http-method, url, synch-or-asynch) initialisation, with URL, HTTP method to use and synchronous or asynchronous flag setrequestheader(label, value) before sending send(content) make the call, including text or XML content abort( ) abort current call 2000-12 CRS Enterprises Ltd 11

XMLHttpRequest Properties onreadystatechange event handler called whenever readystate changes readystate current status of request status HTTP status responsetext response as text responsexml response as XML statustext status as text 2000-12 CRS Enterprises Ltd 12

XMLHttpRequest Security can only be run on a web page stored on a web server e.g. not your C: drive can only fetch files from the same site that the page is on www.foo.com/a/b/c.html can only fetch from www.foo.com 2000-12 CRS Enterprises Ltd 13

The readystate Property For asynchronous operation Value is integer between 0 and 4 0 not not initialised --open() not not yet yet called 1 initialised but but send() not not called 2 send() called but but no no response from from server 3 data data being received from from server 4 request is is complete Use event handler to be notified of changes to value Some browser inconsistencies with state 3 2000-12 CRS Enterprises Ltd 14

Creating the XMLHttpRequest Object Beware browser incompatibility different object name in IE Use initialisation function to hide differences var varreq; req; function initrequest() {{ if if (( window.xmlhttprequest )){{ req req = new new XMLHttpRequest(); }} else else if if (( window.activexobject )){{ isie isie = true; true; req req = new new ActiveXObject("Microsoft.XMLHTTP"); }} }} // // req reqnow available for for use, use, browsers now now support // // the the same same properties and and methods 2000-12 CRS Enterprises Ltd 15

Preparing and Sending The Request Set event handler <input type="text" size="20" id="userid" name="id" onchange="checkuserid();" /> Initialise XMLHttpRequest object for call function checkuserid( useridelem ) { initrequest(); // from before req.onreadystatechange = handleresponse; if (!target ) { target = document.getelementbyid("userid" ); } var url = "validate?id=" + encode(target.value); req.open( "GET", url, true ); req.send( null ); // Make the call } 2000-12 CRS Enterprises Ltd 16

At The Server (Java Servlets) doget() method checks the userid Sends back appropriate XML with result public public void void doget(httpservletrequest req, req, HttpServletResponse res) res) throws throws IOException, ServletException {{ String String result; result; String StringtargetId = req.getparameter("id"); res.setcontenttype("text/xml"); if if ((targetid!=!= null) null) && &&(isvalidid(targetid))) result result = "<valid>true</valid>"; else else result result = "<valid>false</valid>"; res.getwriter().write(result); }} 2000-12 CRS Enterprises Ltd 17

Processing The Result Callback function registered as onreadystatechange event handler function handleresponse () (){{ if if (( req.readystate == == 4 )){{ // // Request completed if if (( req.status == == 200 200 )){{ // // All All OK OK if if (( req.getresponseheader() == == "text/xml" )){{ // // We We have have XML, XML, retrieve it it as as a DOM DOM document var vardoc = req.responsexml; // // Now Now process the the response }} }} }} }} 2000-12 CRS Enterprises Ltd 18

Using The Result To display a message on the validity of the user id called from response handler, using DOM functions to alter document content function setuidmsg(msg){ var var el el = document.getelementbyid("useridmsg"); var var text text = (msg (msg == == "false") "false")? "Invalid ID" ID" ::"Valid "Valid ID"; ID"; }} var var body body = document.createtextnode(text); if if (el.childnodes[0] )){{ el.replacechild(body, el.childnodes[0]); // // replace replace existing }} else else {{ el.appendchild(body); <body> } } <div } <div id="useridmsg"></div> } </body> 2000-12 CRS Enterprises Ltd 19

Request Timeouts What if the server does not respond? Synchronous requests block entire browser Asynchronous requests can be timed out Use Window.setTimeout() with XMLHttpRequest.abort() If response arrives before timeout, use Window.clearTimeout() 2000-12 CRS Enterprises Ltd 20

Response Encodings - XML For structured data, XML is often used // // Server Server side side code, code, generating response resp.setcontenttype("text/xml"); resp.setheader("cache-control", "no-cache"); resp.getwriter().write("<book> <author>john Doe</author> <title>all About About Ajax</title> </book>"); if if (( req.getresponseheader() == == "text/xml" )){{ // // We We have have XML, XML, retrieve it it as as a DOM DOM document var var doc doc = req.responsexml; // // Now Now pull pull out out data data using using JavaScript DOM DOM functions var var author author = doc.childnodes[0].text }} 2000-12 CRS Enterprises Ltd 21

Response Encodings - JSON... JavaScript Object Notation (JSON) easy to convert to JavaScript object use eval or a parser (for more security) // // Server Server side side code, code, generating response resp.setcontenttype("text/javascript"); resp.setheader("cache-control", "no-cache"); resp.getwriter().write("[ "author": "John "John Doe", Doe", "title": "title":"all "All About About Ajax" Ajax" ]]"); "); [[ "author": "John "John Doe", Doe", "title": "title":"all "All About About Ajax" Ajax" ]] 2000-12 CRS Enterprises Ltd 22

... JSON Can make cross-domain requests unlike AJAX which uses XMLHttpRequest yo make cross-domain requests, just dynamically create your <script> tags using the DOM and add a src attribute to point to the desired JSON URL CSS can also be expressed in JSON JavaScript's eval() method to convert the string into a real JavaScript object var data = eval('(' + req.responsetext + ')'); 2000-12 CRS Enterprises Ltd 23

JavaScript/AJAX Toolkits 2000-12 CRS Enterprises Ltd 24

JavaScript/AJAX/JSON Toolkits jquery http://jquery.com GWT (Google Web Toolkit) http://code.google.com/webtoolkit Dojo http://www.dojotoolkit.org YUI (Yahoo! User Interface Library) http://developer.yahoo.com/yui DWR http://getahead.org/dwr script.aculo.us http://script.aculo.us Prototype http://www.prototypejs.org 2000-12 CRS Enterprises Ltd 25

Other Tools Firefox Extensions Firebug view the XMLHttpRequests Selenium Record scripts and replay them! JSView See All JavaScript/CSS with a click Modify Headers (what the name implies!) NoScript Turn off or limit scripts Fiddler and other Proxys watch all client-server traffic 2000-12 CRS Enterprises Ltd 26

jquery jquery wrapper wraps a set of DOM elements jquery is also an object <html> <html> <head> <script <script type="text/javascript" src="jquery.js"></script> <script <script type="text/javascript"> $(document).ready(function() {{ $("h1").css("color", "blue"); }) }) </script> need to know the CSS </head> selector syntax <body> <h1>test Page</h1> </body> </html> 2000-12 CRS Enterprises Ltd 27

GWT (Google Web Toolkit) Open source Java software development framework Develop Web applications as if they were Swing-like GUIs Easier AJAX application development You write your front end in Java using any Java IDE available (e.g. Eclipse, JProfiler, JUnit, IntelliJ ) GWT complier will automatically convert it into browser-complaint JavaScript and HTML Confirm that the Web App. Runs successfully in each browser GWT Architecture GWT Java-to-JavaScript Compiler: Java-to-JavaScript compiler GWT Hosted Web Browser: run and execute your GWT applications JRE emulation library: contains JavaScript implementations of the most widely used classes in the Java standard class library. GWT Web UI class library: set of custom interfaces and classes that let your create web browser "widgets with use of CSS 2000-12 CRS Enterprises Ltd 28

Dojo Dojo is an open-source JavaScript toolkit Widely used Large range of functionality Basic layout Fonts, images etc Animations Ajax Supports all major browsers Preferred toolkit in Fidelity http://www.dojotoolkit.org 2000-12 CRS Enterprises Ltd 29

Dojo - Getting Started Basic capabilities implemented in file dojo.js Dojo provides hook to ensure that document is completely loaded before functionality is applied Hides cross-browser differences <html> <html> <head> <title>dojo Toolkit Toolkit Test Test Page</title> <!-- <!--load the the dojo dojo toolkit toolkit base base --> --> <script <script type="text/javascript" src="js/dojo/dojo.js" djconfig="parseonload:true, isdebug:false"></script> <script <script type="text/javascript"> var var init init = function() {{ alert("page is is ready..."); }; }; dojo.addonload(init); </script> </head>...... 2000-12 CRS Enterprises Ltd 30

YUI (Yahoo! User Interface Library) Collection of JavaScript and CSS resources Makes RIA (Rich Internet Applications) easier to build Open source Yahoo! User Interface Library components Utilities UI Controls CSS resources Yahoo! Design Patterns Library easily implement design patterns 2000-12 CRS Enterprises Ltd 31

DWR (Direct Web Remoting) Java open source library facilitates writing AJAX web sites Two components: Java Servlet running on the server to process requests and sends responses back to the browser. JavaScript running in the browser to send requests and can dynamically update the webpage. Dynamically generates JavaScript feels like the execution is happening in the browser, but... server is executing the code DWR converts data back and forth using a callback function 2000-12 CRS Enterprises Ltd 32