0
AJAX Transport Layer

       Siarhei Barysiuk
s.barysiuk@sam-solutions.net
Our roadmap
AJAX... not just for toilet cleaning anymore


                • AJAX = Asynchronous JavaScript and XML

                •...
Ajax: Classic Web Application
                      1) Browser makes request to server
                      2) Server sen...
Ajax: Ajax Web Application
                      1) Browser makes request to server
                      asynchronously
 ...
XMLHttpRequest
XMLHttpRequest: Fetching data flow

                       1) User generates an event (e.g. button click)
                 ...
XMLHttpRequest: XHR Interface
                        event listener                                     XHR State
   // e...
XMLHttpRequest: How to get XHR
function getXHR() {
	 var request = null;
	
	 if (typeof XMLHttpRequest != 'undefined') {
	...
XMLHttpRequest: Using XHR
var READY_STATE_COMPLETE=4;

var request = getXHR();   1
	
                                     ...
XMLHttpRequest: An example
A classic example is linked drop-downs.



                               Regions    Cities
XMLHttpRequest: Supported methods
• GET
Requests a representation of the specified resource. By far the most common method ...
XMLHttpRequest: GET method
var READY_STATE_COMPLETE=4;
                              1
var request = getXHR();
	
         ...
XMLHttpRequest: POST method
var READY_STATE_COMPLETE=4;
                              1
var request = getXHR();
	
        ...
XMLHttpRequest: Features

• object available in IE/Mozilla/Opera/Safari
• synchronous and asynchronous requests
• POST and...
XMLHttpRequest: Pros and Cons

+ not limited to XML
+ asynchronous calls
+ can receive HTTP status codes/headers
+ support...
XMLHttpRequest: Same-origin policy
The philosophy of the same origin policy is simple: the browser should
not trust conten...
Questions?
iframe transport
iframe transport: Fetching data flow

                         1) User generates an event (e.g. button click)
             ...
iframe transport: How to use

var iframe = document.createElement(quot;iframequot;); 1
iframe.width=quot;0quot;;
iframe.he...
iframe transport: How to use

var iframe = document.createElement(quot;iframequot;); 1
iframe.width=quot;0quot;;
iframe.he...
iframe transport: An example
 Linked drop-downs example.



                               Regions   Cities
iframe transport: Pros and Cons
+ wide browser compatibility

- browser history
- iframe not supported by XHTML strict
- c...
iframe transport: Cross-domain policy
...
iframe.src = this.url + quot;?quot; + this.getRequestString();
...
             ...
Questions?
img cookie transport
img cookie transport: What is cookie?
Technically, cookies are arbitrary pieces of data chosen by the Web server and
sent ...
img cookie transport: Cookies limitations
Relevant count of maximum stored cookies per domain for the major browsers
are:
...
img cookie transport: Fetching data flow




 1) Create <img> with request URL and append it to body. Browser makes a
 requ...
img cookie transport: An example
...

var img = document.createElement(quot;imgquot;); 1
img.width = quot;0quot;;
img.heig...
img cookie transport: Pros and Cons
+ lightweight
+ really really extra wide compatibility

- limited data due to GET and ...
Questions?
script transport
script transport: Fetching data flow




     1) Create <script> element with given src attribute. Browser makes
     reque...
script transport: JSON? What is it?

    JSON (JavaScript Object Notation) is a lightweight data-interchange format.

• It...
script transport: JSON? What is it?
{
	 {quot;menuquot;: {
  	 	 quot;idquot;: quot;filequot;,
   	
  	 	 quot;valuequot;:...
script transport: An example
del.icio.us mashup
script transport: Pros and Cons
+ exempt from Same Origin restriction
+ less overhead (headers, cookies)
- JSON only
- GET...
script transport: JSONP extension
Pass a name of callback function as jsonp parameter.


http://somehost:port/path?jsonp=f...
Questions?
comet
comet: Intro
Named after kitchen cleaning.
comet: What is it?

Fundamentally, [Comet applications] all use long-lived HTTP
connections to reduce the latency with whi...
comet: Who’s using it?
comet: Classic Ajax Application
comet: Comet Application
comet: An example
Highly interactive applications like chats, real-time games, etc.
comet: Pros and Cons
+ low latency
+ event-based server push
- client 2 connection limit
- pragmatically requires custom s...
Questions?
AJAX Transport Layer
Upcoming SlideShare
Loading in...5
×

AJAX Transport Layer

3,720

Published on

Day 1 of 7-days "JavaScript and Rich User Interfaces" training for my colleagues. It covers XMLHttpRequest, iframe, img cookie transport, script transport, JSONP, comet.

Published in: Technology
1 Comment
4 Likes
Statistics
Notes
  • interesting presentation . Good idea to run our cars. by Move transport http://www.movetransport.com/ Car Transport, Vehicle Shipping, Auto Transport, Car Shipping, Vehicle Transport
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Views
Total Views
3,720
On Slideshare
0
From Embeds
0
Number of Embeds
12
Actions
Shares
0
Downloads
155
Comments
1
Likes
4
Embeds 0
No embeds

No notes for slide

Transcript of "AJAX Transport Layer"

  1. 1. AJAX Transport Layer Siarhei Barysiuk s.barysiuk@sam-solutions.net
  2. 2. Our roadmap
  3. 3. AJAX... not just for toilet cleaning anymore • AJAX = Asynchronous JavaScript and XML • Ajax is set of technologies that allow web applications to provide rich interaction without whole page refreshing.
  4. 4. Ajax: Classic Web Application 1) Browser makes request to server 2) Server sends HTML/CSS response
  5. 5. Ajax: Ajax Web Application 1) Browser makes request to server asynchronously 2) Server sends XML/JSON response 3) AJAX Engine processes response
  6. 6. XMLHttpRequest
  7. 7. XMLHttpRequest: Fetching data flow 1) User generates an event (e.g. button click) 2) System creates an XMLHttpRequest and configures with request parameters. 3) The XMLHttpRequest object makes an asynchronous request to the web server. 4) Web server returns XML(other) object with data. 5) The XMLHttpRequest object receives the XML data and calls a callback to process it.
  8. 8. XMLHttpRequest: XHR Interface event listener XHR State // event handler attribute EventListener onreadystatechange; // state const unsigned short UNSENT = 0; const unsigned short OPENED = 1; const unsigned short HEADERS_RECEIVED = 2; open const unsigned short LOADING = 3; const unsigned short DONE = 4; send readonly attribute unsigned short readyState; abort // request void open(in DOMString method, in DOMString url); void open(in DOMString method, in DOMString url, in boolean async); void open(in DOMString method, in DOMString url, in boolean async, in DOMString user); void open(in DOMString method, in DOMString url, in boolean async, in DOMString user, in DOMString password); void setRequestHeader(in DOMString header, in DOMString value); void send(); void send(in DOMString data); void send(in Document data); void abort(); Response // response (Text/XML) DOMString getAllResponseHeaders(); DOMString getResponseHeader(in DOMString header); readonly attribute DOMString responseText; readonly attribute Document responseXML; readonly attribute unsigned short status; readonly attribute DOMString statusText;
  9. 9. XMLHttpRequest: How to get XHR function getXHR() { var request = null; if (typeof XMLHttpRequest != 'undefined') { request = new XMLHttpRequest(); } else { try { request = new ActiveXObject(quot;Msxml2.XMLHTTPquot;); } catch (e) { try { request = new ActiveXObject(quot;Microsoft.XMLHTTPquot;); } catch (e) {} } } return request; }
  10. 10. XMLHttpRequest: Using XHR var READY_STATE_COMPLETE=4; var request = getXHR(); 1 2 request.onreadystatechange = function() { if (request.readyState == READY_STATE_COMPLETE) { //200 OK if (request.status == 200) { 5.1 //process data } //Some error 5.2 else { //process error } } }; request.open(method,url,true); 3 request.send(null); 4
  11. 11. XMLHttpRequest: An example A classic example is linked drop-downs. Regions Cities
  12. 12. XMLHttpRequest: Supported methods • GET Requests a representation of the specified resource. By far the most common method used on the Web today. • POST Submits data to be processed (e.g. from an HTML form) to the identified resource. The data is included in the body of the request. This may result in the creation of a new resource or the updates of existing resources or both. • HEAD Asks for the response identical to the one that would correspond to a GET request, but without the response body. This is useful for retrieving meta-information written in response headers, without having to transport the entire content. • PUT Uploads a representation of the specified resource. • DELETE Deletes the specified resource. • OPTIONS This method allows the client to determine the options and/or requirements associated with a resource.
  13. 13. XMLHttpRequest: GET method var READY_STATE_COMPLETE=4; 1 var request = getXHR(); 2 request.onreadystatechange = function() { if (request.readyState == READY_STATE_COMPLETE) { //200 OK if (request.status == 200) { 5.1 //process data } //Some error else { 5.2 //process error is asynchronous? } } }; request.open(quot;GETquot;, quot;/path?param1=value1&param2=value2quot;,true); 3 request.send(null); 4
  14. 14. XMLHttpRequest: POST method var READY_STATE_COMPLETE=4; 1 var request = getXHR(); 2 request.onreadystatechange = function() { if (request.readyState == READY_STATE_COMPLETE) { //200 OK if (request.status == 200) { 5.1 //process data } //Some error else { 5.2 //process error is asynchronous? } } }; request.open(quot;POSTquot;, quot;/pathquot;,true); 3 request.send(quot;param1=value1&param2=value2quot;); 4
  15. 15. XMLHttpRequest: Features • object available in IE/Mozilla/Opera/Safari • synchronous and asynchronous requests • POST and GET support
  16. 16. XMLHttpRequest: Pros and Cons + not limited to XML + asynchronous calls + can receive HTTP status codes/headers + supported GET and POST - back button problems - same-origin policy
  17. 17. XMLHttpRequest: Same-origin policy The philosophy of the same origin policy is simple: the browser should not trust content loaded from arbitrary websites. The term quot;originquot; is defined using the domain name, protocol and port. URL Outcome Reason http://www.example.com/dir2/other.html Success Same protocol and host http://www.example.com/dir/inner/other.html Success Same protocol and host http://www.example.com:81/dir2/other.html Failure Same protocol and host but different port https://www.example.com/dir2/other.html Failure Different protocol http://en.example.com/dir2/other.html Failure Different host http://example.com/dir2/other.html Failure Different host
  18. 18. Questions?
  19. 19. iframe transport
  20. 20. iframe transport: Fetching data flow 1) User generates an event (e.g. button click) 2) System creates a hidden IFrame and configures with request parameters. 3) The IFrame element makes an request to the web server. 4) Web server returns XML(other) object with data. 5) The IFrame object receives the XML data and fires a load event.
  21. 21. iframe transport: How to use var iframe = document.createElement(quot;iframequot;); 1 iframe.width=quot;0quot;; iframe.height=quot;0quot;; ... iframe.onload = bind(this.callback, this); 2 ... GET iframe.src = this.url + quot;?quot; + this.getRequestString(); 3 ... document.body.appendChild(this.iframe); 4 In order to use POST you need to { } create <form> and fill it dynamically.
  22. 22. iframe transport: How to use var iframe = document.createElement(quot;iframequot;); 1 iframe.width=quot;0quot;; iframe.height=quot;0quot;; ... iframe.onload = bind(this.callback, this); 2 ... GET iframe.src = this.url + quot;?quot; + this.getRequestString(); 3 ... document.body.appendChild(this.iframe); 4 <iframe> <!-- ... --> <script type=quot;text/javascriptquot;> window.parent.someFunction(/*data here*/); </script> <!-- ... --> </iframe>
  23. 23. iframe transport: An example Linked drop-downs example. Regions Cities
  24. 24. iframe transport: Pros and Cons + wide browser compatibility - browser history - iframe not supported by XHTML strict - cross-domain policy
  25. 25. iframe transport: Cross-domain policy ... iframe.src = this.url + quot;?quot; + this.getRequestString(); ... different than current <iframe> http://host:port/path <!-- ... --> <script type=quot;text/javascriptquot;> window.parent.handleIframeResponse(/*data here*/); </script> <!-- ... --> </iframe>
  26. 26. Questions?
  27. 27. img cookie transport
  28. 28. img cookie transport: What is cookie? Technically, cookies are arbitrary pieces of data chosen by the Web server and sent to the browser.
  29. 29. img cookie transport: Cookies limitations Relevant count of maximum stored cookies per domain for the major browsers are: Firefox 2 Firefox 3 Opera 9.30 IE 6 IE 7 Safari has no limit. Safari 0 12.5 25.0 37.5 50.0 Cookies must be smaller than 4 kilobytes. Internet Explorer imposes a 4KB total for all cookies stored in a given domain.
  30. 30. img cookie transport: Fetching data flow 1) Create <img> with request URL and append it to body. Browser makes a request to the server. 2) Server sets cookies and sends response to the client. 3) Client checks cookies after some time interval.
  31. 31. img cookie transport: An example ... var img = document.createElement(quot;imgquot;); 1 img.width = quot;0quot;; img.heigth = quot;0quot;; img.src = this.url + quot;?quot; + this.getRequestString(this.data); 2 ... document.body.appendChild(this.img); 3 ... setTimeout(bind(this.callback,this),this.interval); 4
  32. 32. img cookie transport: Pros and Cons + lightweight + really really extra wide compatibility - limited data due to GET and cookie limits
  33. 33. Questions?
  34. 34. script transport
  35. 35. script transport: Fetching data flow 1) Create <script> element with given src attribute. Browser makes request to the server. 2) Server returns JSON data wrapped in function call. 3) Client runs function in own context.
  36. 36. script transport: JSON? What is it? JSON (JavaScript Object Notation) is a lightweight data-interchange format. • It is easy for humans to read and write. • It is easy for machines to parse and generate. • It is based on a subset of the JavaScript Programming Language. • It is a text format that is completely language independent.
  37. 37. script transport: JSON? What is it? { {quot;menuquot;: { quot;idquot;: quot;filequot;, quot;valuequot;: quot;Filequot;, quot;popupquot;: { quot;menuitemquot;: [ {quot;valuequot;: quot;Newquot;, quot;onclickquot;: quot;CreateNewDoc()quot;}, {quot;valuequot;: quot;Openquot;, quot;onclickquot;: quot;OpenDoc()quot;}, {quot;valuequot;: quot;Closequot;, quot;onclickquot;: quot;CloseDoc()quot;} ] } } } }
  38. 38. script transport: An example del.icio.us mashup
  39. 39. script transport: Pros and Cons + exempt from Same Origin restriction + less overhead (headers, cookies) - JSON only - GET method only
  40. 40. script transport: JSONP extension Pass a name of callback function as jsonp parameter. http://somehost:port/path?jsonp=funcName&param1=value1 jsonp + quot;(quot; + jsonResult + quot;);quot;
  41. 41. Questions?
  42. 42. comet
  43. 43. comet: Intro Named after kitchen cleaning.
  44. 44. comet: What is it? Fundamentally, [Comet applications] all use long-lived HTTP connections to reduce the latency with which messages are passed to the server. In essence, they do not poll the server occasionally. Instead the server has an open line of communication with which it can push data to the client.
  45. 45. comet: Who’s using it?
  46. 46. comet: Classic Ajax Application
  47. 47. comet: Comet Application
  48. 48. comet: An example Highly interactive applications like chats, real-time games, etc.
  49. 49. comet: Pros and Cons + low latency + event-based server push - client 2 connection limit - pragmatically requires custom server component Cometd LightStreamer ...
  50. 50. Questions?
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×