Your browser doesn't support the features required by impress.js, so you are presented with a simplified version of this presentation.

For the best experience please use the latest Chrome, Safari or Firefox browser.


AJAX

Prof. Cesare Pautasso
http://www.pautasso.info
[email protected]
@pautasso

Asynchronous JavaScript and XML

Asynchronous JavaScript (and XML)

JSON is the new XML

Web application Architecture

Very Thin Client

Client/Server

Rich Client

General Architecture

The server is a database

The browser is a terminal

Rich vs. Thin Client

What about security?

Web servers should not ever run
any code sent by a Web browser

Interconnect

How to connect the client with the server?

How to connect the server with the client?

  • Pull: Fetch and refresh output data
  • Push: Notify client about state changes

Web 1.0 Architecture

Web 1.0 Architecture - Problems

Web 2.0 Architecture

Advantages

Problems

AJAX

AJAX combines different technologies:

Synchronous Interaction

The user waits for the server to process each request

Asynchronous Interaction

The UI thread is never blocked since server interactions run in the background

XMLHttpRequest (GET, Synch)

function GET(url) {
  var xhr = new XMLHttpRequest();
  xhr.open("GET", url, false);
  xhr.send(null); 
  //this will continue after the response has arrived
  if (xhr.status == 200) 
    return xhr.responseText;
  else
    //handle error
}

false = synchronous

responseText contains the JSON string to be parsed

XMLHttpRequest (GET, Asynch)

function GET(url, callback) {
  var xhr = new XMLHttpRequest();
  xhr.open("GET", url, true);
xhr.onreadystatechange = function() { if (xhr.readyState == 4) { if (xhr.status == 200) callback(xhr.responseText); else //handle error } }
xhr.send(null); //this will continue immediately }

true = asynchronous

readyState
0uninitialized
1opened
2sent
3receiving
4complete

XMLHttpRequest (POST, Asynch)

function POST(url, params, callback) {
  var xhr = new XMLHttpRequest();
  xhr.open("POST", url, true);
  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
      if (xhr.status == 200) 
        callback(xhr.responseText);
    }
  }
  xhr.setRequestHeader("Content-Type",
                  "application/x-www-form-urlencoded");
  xhr.send(params); 
  //this will continue immediately 
}

Event Notification

Long Polling

The client polls the server for updates which are sent only when they become available

Server Push

The server misuses HTTP by keeping the response open forever

HTML5 WebSockets

The original HTTP connection is upgraded to use the WebSocket protocol

WebSocket (Client)

var location = "ws://www.nyse.com/GOOG";
//open a WebSocket connection with the server
var socket = new WebSocket(location);
socket.onopen = function(event) { 
  //connection established
  //send a message to the server
  socket.send("Hello, WebSocket");
}
socket.onmessage = function(message) { 
  //message received from the server 
  console.log(message.data);
}
socket.onclose = function(event) { 
  //connection closed by the server 
  console.log("closed");
}
socket.onerror = function(event) { 
  //communication error 
  console.log("error!"+event);
}

WebSocket (Server)

var WebSocketServer = require('websocket').server;
var http = require('http');

var server = http.createServer(
function(request, response) {
  console.log('HTTP Request: ' + request.url);
  response.writeHead(404);
  response.end();
});
server.listen(8888);

// Create a WebSocket Server wrapping the HTTP Server
wsServer = new WebSocketServer({
    httpServer: server
});

//Check if the request origin is allowed to connect
function originIsAllowed(origin) { return true; }

wsServer.on('request', function(request) {
  if (!originIsAllowed(request.origin)) {
    request.reject(); return;
  }
  // Connection Accepted
  var connection = request.accept(null, request.origin);
  var echo = function(message) {
    if (message.type === 'utf8') {
      console.log('Received: ' + message.utf8Data);
      connection.sendUTF(message.utf8Data);
    }
    else if (message.type === 'binary') {
      console.log('Received binary data');
      connection.sendBytes(message.binaryData);
    }
  }
  connection.on('message', echo);
  connection.on('close', 
    function(reasonCode, description) {...});
});

References

Use a spacebar or arrow keys to navigate