Ajax Programming

scaredbaconSoftware and s/w Development

Jul 4, 2012 (4 years and 9 months ago)

360 views

Page 1
Ajax Programming
BaSoTi
Ajax and Advanced Javascript Programming
Overview
What is Ajax?
XHR: XMLHttpRequest
Advanced Javascript Programming Libraries
BaSoTi
Ajax and Advanced Javascript Programming
JQuery
JSON and JSONP
What is AJAX ?
Not a cleansing agent
In computer science

Not a new technology

Rather a kind of design philosophy
BaSoTi
Ajax and Advanced Javascript Programming
3

Basis of most Web 2.0 sites
What is AJAX ?
Not a football club either
BaSoTi
Ajax and Advanced Javascript Programming
Page 2
Users are frustrated . . .
World Wide Wait
Static Web Applications
Internet-Applications
are not Desktop-Applications
BaSoTi
Ajax and Advanced Javascript Programming
5

Clicking from page to page

At first: Not reaction to the user

Lack of interaction

Unclear "undo" of the last step
What is the semantics of a "back"?

Unclear "refresh" of the screen
What is the semantics of a "reload"?
HTTP Reload Cycles
User
User
User
HTTP
GET
Request
wait
wait
BaSoTi
Ajax and Advanced Javascript Programming
6
Server
Server
Server Response
Some 100kB
complete HTML
page
wait
AJAX Reload Cycles
User User
XHR
Request
Dynamic page
adaption of
some 5 kB
BaSoTi
Ajax and Advanced Javascript Programming
7
Server Server
Server response
Some 5 kB
of data
AJAX ENGINE
AJAX is
AjaX is Asynchronous Javascript XMLHTTPRequest
Miesleading acronym
Examples:
1.
Access an HTML page containing a widget with an onclick handler
2.
Upon click on widget an asynchronous server connection is opened
BaSoTi
Ajax and Advanced Javascript Programming
8
3.
HTML page remains the same (no new pageload)
4.
Transmit a few data
5.
Modify / extend the HTML page by adding a few elements
The differences:
1.
Asynchronous: GUI not blocked while waiting for result
2.
No page clear:Page is not blanked and refilled with result
3.
Handler:Result not fed to layout engine but to result handler
Page 3
Concepts
and Technologies
Loosely coupled communication
Asynchronous communication XMLHttpRequest, Sockets
Variants of synchronous comm:Multipart MIME, Server Sockets
Lightweight Processing in n-tier Architecture
Client
-
Side Scripting
Javascript
BaSoTi
Ajax and Advanced Javascript Programming
9
Client
-
Side

Scripting
Javascript
Server-Side Code Generation PHP, Java – based Ajax kits
OO document modell with seperated representation
Markup HTML, XML, XHTML
Representation-transformation CSS, XSLT
DOM – manipulation innerHTML, JS DOM
JavaScript
NS 2.0B3
FF 1.0
CSS
ECMAScript
DOM 1
Flash 3
Flash 8
Java Applet
E4X
SVG
FF 1.5 Beta
XSL-T
XHTML
SVG
WSDL
Mozilla 1.0
Already early
historical development
BaSoTi
Ajax and Advanced Javascript Programming
10
96
97
98
99 00 01 02 03 04
05
CSS
IFrames
IE 3
JScript
Browser Wars
DOM
IE 4
XSL-T
XML
IE 5
XMLHTTP
DOM 3
XForms
XSL-T 2
The Web Depression
Web 2.0
RDF
It Works!
IE 6
""Inventor" of Ajax
James Garett
“What’s new is the prominent use of these techniques in real-world
applications to change the fundamental interaction model of the Web.
Ajax is taking hold now because these technologies and the industry’s
understanding of how to deploy themmost effectively have taken time
BaSoTi
Ajax and Advanced Javascript Programming
11
understanding

of

how

to

deploy

them

most

effectively

have

taken

time

to develop.”
“We don’t know yet [for what types of applications AJAX is best suited].
Because this is a relatively new approach, our understanding of where
Ajax can best be applied is still in its infancy. Sometimes the traditional
web application model is the most appropriate solution to a problem.”
XMLHttpRequest
BaSoTi
Ajax and Advanced Javascript Programming
Page 4
XMLHttpRequest
XMLHttpRequest is a Javascript object

opens a HTTP connection (request)

sends back the answer (response)
Request can be

GET request
BaSoTi
Ajax and Advanced Javascript Programming
13

GET request with query encoding in url-encoded format
Example: http://www.bsp.de/index.php?user=cap&pw=hallo

POST request with url-encoded body-element
Temporal behaviour could be

Asynchronous:Activation returns immediately and without a result
Upon response: Call an event handler

Synchronous:Activation returns only with result
XMLHttpRequest
// define new XMLHttpRequest object
var r = new XMLHttpRequest();
// prepare object for opening (do not open now !!)
r.open ("get", "http://www.bsp.de/?a=1&b=2", true);
BaSoTi
Ajax and Advanced Javascript Programming
14
// provide handler
r.onreadystatechange = function () {
if (r.readyState==4) { // status 4 = completed
var t = document.getElementById("showContent");
t.innerHTML = r.responseText; // uses response
}
// go ! (null, since a GET has no body)
r.send(null);
XMLHttpRequest
Generate a new object
In normal browsers as expected by W3C standard

var r = new XMLHttpRequest();
With (older) Bill Gates browsers proprietary:
BaSoTi
Ajax and Advanced Javascript Programming
15

var r = new ActiveXObject("Msxml2.XMLHTTP");-or-

var r = new ActiveXObject("Microsoft.XMLHTTP");

As of IE 7: Comformant to standard
XMLHttpRequest
abort ( )

Stop processing in case of timeout or error
open ( method, uri, [async, [username, [password]]] )

Prepare object for sending, but do not send
BaSoTi
Ajax and Advanced Javascript Programming
16
send ( content )

Send and

Wait in the synchronous case

Proceed in the asynchronous case

content is body for POST, for the other methods: null
Page 5
XMLHttpRequest
onreadystatechange ( )

Handler, which is called when readyState attribute of theobject changes
readyState

Attribute containing information on the advancement of the communication process
responseText
BaSoTi
Ajax and Advanced Javascript Programming
17
responseText

Contains HTML in text form (ie. as a string object)
responseXML

Contains XML in DOM form (ie. as an object)
status

Contains further status information
More details: See documentation
GET or POST
GET

URL including all parameters visible in log (and browser location line)

Very easy to manipulate, even for the end user (need no packet sniffer, need only
keyboard)

Firewall might filter the URL

Firewall and browsers have URL length restriction (1 – 2 k Characters)
BaSoTi
Ajax and Advanced Javascript Programming
POST

Posts are usually not cached

Posts when part of an HTML page leads to reload / back button issues

Body must be url-encoded, headers needs Mime-Type url-encoded
18
Synchronous or asynchronous?
Synchronous

It is no longer Ajax but should be called Sjax 

Could be useful to prevent other interactions of the user (kind of modal dialogue)

Can lead to a short "hanging" of the browser

Suggestion:Asynchronous use
BaSoTi
Ajax and Advanced Javascript Programming
19
Asynchronous

Classical Ajax case, but requires

Some thoughts on timeout

Some thoughts on errors

Some thoughts on multiple requests

"Loading" indication to the user
Synchronous or asynchronous
Timeout Problem
Timeout Problem Server responds later than expected

Later than expected by user:Not so bad

Later than expected by app:Very bad
Issue: Handler does not find expected context
into which received content should be placed
BaSoTi
Ajax and Advanced Javascript Programming
20
Solution 1:Defensive Programming

Handler must always check assumptions on present DOM elements
Solution 2:Explicit Timeout

Setup a timeout

Upon timeout, cancel the request with abort()
Page 6
Synchronous or asynchronous
User Problem
User Problem Impatient user activates function a second time
Solution 1:Idempotent Programming

Client and Server expect a double invocation

Make function call idempotent

Eg: Use prior state (if account equals 200, then add 50 else nop)

Eg:Use sequence number for transactions
BaSoTi
Ajax and Advanced Javascript Programming
21

Eg:

Use

sequence

number

for

transactions
Solution 2:Lock GUI until interaction completed or aborted

Effective solution but prevents user from issuing parallel requests
Solution 3:Provide User Feedback

Eg: "Really order a second book?"
User Feedback
Inform User:

1. Idea:Show busy cursor
How:Changes CSS style or CSS class
Problem:Some browser only update the cursor after a mouse Entry event

2. Idea:Show informative window or animated image
BaSoTi
Ajax and Advanced Javascript Programming
22
How:Via CSS display / visibility attribute
Modal Dialogues in Javascript
Modal Dialogue:Force user input before user can continue
Browser Based:

alert() Get user to confirm a fact, before going on

confirm() Get user to confirm or cancel, before going on

prompt() Get user to make a single textfiled input, before going on
BaSoTi
Ajax and Advanced Javascript Programming

Style is the "pure" "grey" browser style, cannot be themed nicely
CSS Based:

Position div with higher z-index on the GUI

#modalBackground { position: fixed; left: 0; top: 0;
width: 100%; height: 100%; }

Does not work with IE 6 and older
Handle window scroll and resize events
Advanced Javascript
Programming Toolkits
BaSoTi
Ajax and Advanced Javascript Programming
Page 7
Necessity of Tools
Browser dependencies (Javascript, CSS, HTML, DOM, client-side services)
Support by IDEs is problematic
Large number of low-level technologies raises entry barrier
Code reuse
Highy complex, highly performant widget code

Eg: Tree with drag-and-drop and load-and-cache-on-demand
BaSoTi
Ajax and Advanced Javascript Programming
25
Ajax Toolkits
Types
Client-side Toolkit

Paradigm:Programmer develops client-side pages
Use of server-side functions via URL

Toolkit:Reuseable Javascript / CSS / HTML Code
Code, functions, patterns, widgets
Standardised client-side tasks
BaSoTi
Ajax and Advanced Javascript Programming
26

Interface:HTML, XML, JSON produced by server, handled by kit
Dynamic page adaptation and GUI behaviour
Server-side Toolkit

Paradigm:Page generation and shipping (HTML, JS, CSS, XML, XSLT, ... )

Toolkit:Perl, PHP, Java, Python functions for page generation

Interface:Mostly HTML with embedded (generated) Javascript
Connection to DB, business, application – Server
Ajax Toolkits
Evaluation
Interface:HTML, XML, XHTML, JSON, usw.

Is the interface technology properly understood (people & programs)

Is the method adequate for the problem ?
Degree of abstraction:

High:Prog. server side, in business-Logic and workflow concepts
BaSoTi
Ajax and Advanced Javascript Programming
27
Not much interference with flow of communication

Low:Prog. client side, connection of client-side modules
Use and focus of toolkits

Reuse of difficult code portions
Eg: Tree with dynamic reload from the data base

Browser independence
jQuery
Very compact framework 31 k minified & gzipped
229 k uncompressed
Cross-browser IE, FF, Safari, Chrome, Opera
Standard compliant Full Css 1-3 selectors
Extensible Plug-in architecture by community
License Open Source
BaSoTi
Ajax and Advanced Javascript Programming
Well established community

Excellent documentation

Active support forum

Own conference
Page 8
ExtJS
Similar to jQuery, but
Many more features Hence heavy weight
More complicated to learn
Hierarchical package structure
Extensible Customized download packages
BaSoTi
Ajax and Advanced Javascript Programming
License Dual licensing model
ExtJs
BaSoTi
Ajax and Advanced Javascript Programming
jQuery concepts
Query Concept

Searching elements in the DOM

Compact and powerful query/ selector mechanism

Extension of CSS 1 – 3 selectors
Postquery functions

Apply
functions
on
the
query
results
BaSoTi
Ajax and Advanced Javascript Programming
31

Apply
functions
on

the
query
results

Yields results or (again) query results (the latter allows chaining)
Chainable Queries

Result of a (top level) query is a set of nodes

Reusult allows post query functions for manipulation, filtering, traversal etc.

Result usually again is a set of nodes

Allows a convenient chaining of postquery functions
Examples
$("p:first").css("fontWeight", "bold");
$("div:hidden").show();
$("div:contains('test')").hide();
$("li:eq(0)").fadeOut();
BaSoTi
Ajax and Advanced Javascript Programming
Page 9
jQuery Selectors (1)
Basic Selectors

All"*"Select all elements

Class".class"Select elements of given class

Element"p"Select elements of tagname p

ID"#id"Select elements with given id attribute

Combination"div, p, span"Select union
BaSoTi
Ajax and Advanced Javascript Programming
Attribute Filters

Select elements based on various properties of their attributes

Append a […] construction to a selector

$('input[value="Hot Fuzz"]');
jQuery Selectors (2)
Non-attribute filter:: followed by keywords
Basic Filters:Connected with list concepts

:first, :last First or last in a list

:eq( <num> ) Number in a list

:focus Currently has the focus

Many more
BaSoTi
Ajax and Advanced Javascript Programming

Eg: $("tr:odd").css("background-color", "#bbbbff");
Child Filters:Connected with tree concepts

:first-child, :last-child, :nth-child (3), :only-child
Content Filters:Connected with contents of the element

:contains(), :empty, :has(), :parent
Visibility Filter:Connected with specific property in rendering

:hidden, :visible
jQuery Selectors (3)
Form:Selects elements of a form

:button, :checkbox, :input, :enabled usw.
Hierarchy:Selects DOM tree relationship

Child parent > child

Descendant ancestor descendant
BaSoTi
Ajax and Advanced Javascript Programming

Next Adjacent previous + next

Next Sibling previous ~ siblings
Additional extensions
jQuery
Postquery Functions: CSS
Modify classes

addClass $("p").addClass("selected")

removeClass $("p").removeClass("selected")

toggleClass Adds if not present, removes if present
Get/ Set size
BaSoTi
Ajax and Advanced Javascript Programming
36

height, width:does not include padding, border, margin

innerHeight, innerWidth:includes padding but not border or margin

outerHeight, outerWidth:includes padding, border and margin
Page 10
jQuery
Postquery Functions: CSS
Get/ Set Position
Get/ Set Scrolling
Get/ Set Arbitrary CSS properties
Hook mechanismto extend the CSS functionality of jQuery
BaSoTi
Ajax and Advanced Javascript Programming
37
jQuery
Postquery Functions: DOM Manipulation
Goal is not the query result but:
Select elements in DOM for subsequent modifications

Example: after adds elements after all matching ones
$("p").after("<b>Hello</b>");
DOM Inside Insertion:append, prepend and variants
BaSoTi
Ajax and Advanced Javascript Programming
38
DOM Outside Insertion:after, before, insertAfter, insertBefore
DOM Around Insertion: unwrap, wrap, wrapAll, wrapInner
DOM Removal:detach, empty, remove, unwrap
DOM Replacement:replaceWith, replaceAll
Attributes:add, remove, get, set of attributes
More:cloning, copying etc.
jQuery
Postquery Functions: DOM Traversal
Filter the results of a query Remove specific elements fromthe query result

filter, end
Amend the results of a query Add specific elements

add, andSelf
BaSoTi
Ajax and Advanced Javascript Programming
39
Extend the results of a query Traverse the DOM

children, parent, parents, parentsUntil, next, nextAll, nextUntil, etc.
Iterate over the results of a query

each( function )
jQuery:
Event Handling
Handler binding

bind method binds handler to all result elements of a query
$("p").bind("click", function(){ alert( $(this).text() ); });
Handler binding and triggering

click method binds function as click handler to all result elements of a query
BaSoTi
Ajax and Advanced Javascript Programming
40
$("p").click( function() { alert("Hello"); } );

click method triggers all handlers of all result elements of a query
$("p").click();

Similar for more events: dblclick, focus, blur, keyup, resize, scroll etc.

load and unload corresponds to javascript events

ready is a jQuery event triggered when the DOM is fully loaded
Page 11
jQuery
Ajax Handling
Support functions for Ajax calls
Convenience functions with many params (and many defaults)
Helpful for doing standard Ajax calls
BaSoTi
Ajax and Advanced Javascript Programming
jQuery
main Ajax driver function (1)
accepts accepted data type
async flag: sync or async
beforeSending callback fct called on XHR object before sending
cache do we accept browser cached responses?
complete callback fct called after everything is done
content regular expression for parsing the response
BaSoTi
Ajax and Advanced Javascript Programming
contentType MIME type used for sending
context context for DOM related callbacks
converter array of response converter functions
crossDomain for specific cases, see docu
data to be sent to server
dataFilter prefiltering function for the result
dataType data type expected from server
jQuery
main Ajax driver function (2)
error error callback function
global shall we trigger global ajax handler?
headers additional http headers to be added to request
ifModified request consider successful only, if response has changed
isLocal see doc
jsonp value to be used in JSONP requests instead of callback=
BaSoTi
Ajax and Advanced Javascript Programming
jsonpCallback name of JSONP callback function
mimeType override the XHR mime type
password to be used upon HTTP access authentication request
processData shall data parameter be treated as an object or not
scriptCharset force charset, if different betwenn local and remote
statusCode map of codes and functions to be called when we receive
the corresponding HTTP status codes
success function to be called on success
jQuery
main Ajax driver function (3)
timeout local timeout value
traditional effect on parameter serialization
type GET or POST
url URL to call
username username used in response to an HTTP authentication request
xhr callback for creating XHR object
BaSoTi
Ajax and Advanced Javascript Programming
xhrFields key-value map of properties to be set in the xhr object
Page 12
Usage example
$.ajax({ type: 'POST',
url: url,
data: data,
success: success,
dataType: dataType });
BaSoTi
Ajax and Advanced Javascript Programming
jQuery
get function
$.get("test.cgi", { name: "John", time: "2pm" },
function(data){
alert("Data Loaded: " + data);
});
$.get(
"
test.php
"
,
BaSoTi
Ajax and Advanced Javascript Programming
$.get( test.php,
function(data){
$('body').append("Name: " + data.name); // John
.append("Time: " + data.time); // 2pm
}, "json");
JSON
Javascript Object Notation
Lighweight notation for serializing objects
Supported data structures

Objekte

Arrays
BaSoTi
Ajax and Advanced Javascript Programming
47

Strings

Boolean

Integer

null
JSON Format
BaSoTi
Ajax and Advanced Javascript Programming
48
Page 13
JSON Format
BaSoTi
Ajax and Advanced Javascript Programming
49
BaSoTi
Ajax and Advanced Javascript Programming
50
BaSoTi
Ajax and Advanced Javascript Programming
51
Example
{
"Creditcard" : "Xema",
"Number" : "1234-5678-9012-3456",
"Owner" : {
"Name" : "Reich",
BaSoTi
Ajax and Advanced Javascript Programming
52
"Firstname" : "Rainer",
"Sex" : "\"männlich\"",
"Hobbies" : [ "Reiten", "Schwimmen", "Lesen" ],
"Age" : null },
"Account" : 1e+3,
"Units" : "EUR"
}
Page 14
Extension to JSONP
JSONP = JSON with Padding
Idea:

Client requests a certain padding to JSON data

Server returns padding plus JSON data

Result is added to the Document
BaSoTi
Ajax and Advanced Javascript Programming
53
Effect:

JSON is placed into "right" Javascript function

More on this in security chapter
JSONP Example (1)
var delicious_callbacks = {}; 
function getDelicious(callback, url) 
{ var uid = (new Date()).getTime(); 
delicious_callbacks[uid] = function () { delete delicious_callbacks[uid]; callback(); }; 
url += "?jsonp=" + encodeURIComponent("delicious_callbacks[" + uid + "]");  
// now add server response to URL as script tag to the document
BaSoTi
Ajax and Advanced Javascript Programming
54
}; 
getDelicious(doSomething, "http://del.icio.us/feeds/json/bob/mochikit+interpreter"); 
JSONP Example (2)
http://del.icio.us/feeds/json/bob/mochikit+interpreter?jsonp=delicious_callbacks%5B12345%5D
delicious_callbacks[12345]([{
"u": "http://mochikit.com/examples/interpreter/index.html",
"d": "Interpreter ‐ JavaScript Interactive Interpreter",
"t": [
BaSoTi
Ajax and Advanced Javascript Programming
55
"mochikit","webdev","tool","tools",
"javascript","interactive","interpreter","repl"
]
}])