08 ajax

61
AJAX Data Transfer Client-Server Apps - The Easy Way

description

 

Transcript of 08 ajax

Page 1: 08 ajax

AJAX Data TransferClient-Server Apps - The Easy Way

Page 2: 08 ajax

Agenda

JSON

Modify DOM by Server Data

Web Sockets

Page 3: 08 ajax

Communication

Different systems use different data formats

Each platform has its own logic

Need to decide on a language or protocol

Page 4: 08 ajax

Requirements

What do we need from such a protocol ?

Page 5: 08 ajax

Requirements

Wide server support

Wide client support

Easy to debug

Pass firewalls

Page 6: 08 ajax

Meet JSON

Page 7: 08 ajax

JSON

Stands for JavaScript Object Notation

Text based

Widely Supported

Simple

{! “name” : “Bob”,! “age” : 19,! “image” : “zombie.png” }

Page 9: 08 ajax

JSON Values

Simple Values

Arrays

Nested Hashes

{! name : “Bob”,! age : 19,! image : “zombie.png” }

KEY VALUE

Page 10: 08 ajax

Simple Values

“text”

number

true

false

null

Page 11: 08 ajax

Arrays

A list of comma separated values enclosed in brackets

[1, 2, 3]

[“a”, “b”, “c”]

[1, 2, [“a”, “b”], “hello”, true]

Page 12: 08 ajax

Objects

A nested data object can also act as a value

Example: { foo : { a : 1, b : 2 } }

Page 13: 08 ajax

JSON - Getting BetterNo need to write JSON by hand

Here’s a partial list of languages which produce JSON objects for you:

ASP, ActionScript, BlitzMax, C, C++, C#, Clojure, ColdFusion, Delphi, Eiffel, Erlang, Go, Haskell, Java, JavaScript, Lasso, Lisp, LotusScript, Lua, Objective C, Objective CAML, Perl, PHP, Python, Qt, Ruby, Tcl, Visual Basic, And More...

Page 14: 08 ajax

JSON Alternatives

XML

Dedicated Format

Page 15: 08 ajax

Using JSON

Page 16: 08 ajax

JSON Use Case

Client ServerServer App

DB

Flights To Paris

Results

{ Flights: [ { departure: “02:00”, price: 600 }, { departure: “06:00”, price: 800 }, { departure: “00:00”, price: 999 } ]}

Page 17: 08 ajax

JSON Use Case

Client request - “Paris”

Server gets request

Server performs DB query

Server creates the response JSON object

Server sends the response to client

Page 18: 08 ajax

Demo: Time Server

Server returning time of day using Ruby & Sinatra

App which shows the data

Page 19: 08 ajax

jQuery Functions

$.get - sends a get request to the server. Takes a url, optional data, success handler and data type.

$.post - sends a post request to the server. Takes a url, optional data, success handler and data type.

Page 20: 08 ajax

get/post Examples

$.get(‘test.php’);

$.post(‘test.php’, { name : ‘john’, time: ‘2pm’ });

$.get(‘test.php’, function(data) { alert(data);});

Page 21: 08 ajax

$.ajax

Gain full control over the request

Can handle errors

get/post are actually just shortcuts for this one

Takes url and settings object

Page 22: 08 ajax

$.ajax Settingserror: error handler callback

success: success handler callback

context: the ‘this’ pointer of callbacks

data: data object to send

url: the url to use

Full docs: http://api.jquery.com/jQuery.ajax/

Page 23: 08 ajax

$.ajax Example

$.ajax({!   type: "POST",!   url: "some.php",!   data: "name=John&location=Boston",!   success: function(msg){!     alert( "Data Saved: " + msg );!   }! });!

Page 24: 08 ajax

Same Origin Policy

Cross origin writes: Allowed

Cross origin embeds: Allowed

Cross origin reads:Denied

Page 25: 08 ajax

But I Want To Implement an API

Use JSONP

Use CORS

Page 26: 08 ajax

JSONP Explained

Use cross origin embeds:<script src="http://www.myapi.com/places"></script>

Script returns function, not data:callback(['home', 'work', 'mobile']);

Page 27: 08 ajax

What’s wrong with JSONP ?

Need to specify a callback as global function

Need to add <script> tag dynamically

Can’t post

Page 28: 08 ajax

CORS To The Rescue

Page 29: 08 ajax

CORS Goal

Differentiate good cross origin request from a malicious one

Page 30: 08 ajax

CORS How

I come from www.friend.com

Please send me /contacts/all.json

Page 31: 08 ajax

CORS How

Browser sends Origin: request header

Server checks Origin to check it’s allowed

Server sends Access-Control-Allow-Origin to let browser know the request was OK

Page 32: 08 ajax

CORS Keep In Mind

Be sure to verify Origin on the server

ASP.NET Howto:http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

Page 33: 08 ajax

Q & A

Page 34: 08 ajax

Practice

Use your favorite Server Side Technology

Implement a mobile wall:

App displays a long list of sentences (the wall)

Each user can add a sentence to the wall

Everyone shares the same wall

Page 35: 08 ajax

Handlebar MustacheJS Templating lib that rocks

Page 36: 08 ajax

Concepts

Create parts of the DOM dynamically by using JavaScript, based on data that is stored as JS objects

Template + Data = HTML

Page 37: 08 ajax

Use CasesData is collected from the server

Data is retrieved form local storage

Data is aggregated from multiple sources

Translationshttp://loveandasandwich.deviantart.com/art/Mustache-Monsterssss-201209873

Page 38: 08 ajax

Selected Librariesmustache.js

handlebars

ejs

pure.js

underscore.js

And many more...

Page 39: 08 ajax

The How

A template looks like normal html code

Special placeholders are inserted in the template

<div class="entry">  <h1>{{name}}</h1>  <span>{{details}}</span></div>

Page 40: 08 ajax

The How

Each template is rendered with a context.

The context is a JavaScript object that provides values for the placeholders

{  name: "Jimmy Jones",  details: "A friend of Ghandi"}

Page 41: 08 ajax

Combined

<div class="entry">  <h1>{{name}}</h1>  <span>{{details}}</span></div>

{  name: "Jimmy Jones",  details: "A friend of Ghandi"}

+

<div class="entry">  <h1>Jimmy Jones</h1>  <span> A friend of Ghandi </span></div>

Page 42: 08 ajax

Demo

Using a template embedded inside the html file as a script

Code: ajax/Handlebars/Demo1/

Page 43: 08 ajax

Using Handlebars

Rendering Objects

Rendering Arrays

Conditional Rendering (if)

Helpers

Page 44: 08 ajax

Rendering Objects

Can use a block expression in the template

This will use a different context for the rendering

Example: With

<div class="entry">  <h1>{{title}}</h1>  {{#with author}}!  <span>By: {{first}} {{last}}</span>!  {{/with}}</div>

var ctx = {  title: "Alice's Adventures in Wonderland",  author: {    first: 'Lewis',    last: 'Carrol'  }};

Page 45: 08 ajax

Rendering Arrays

The each block helper renders each element in an array in its own entry

Inside the block, this refers to the current element

<ul class="people_list">  {{#each people}}!  <li>{{this}}</li>!  {{/each}}</ul>

{  people: [    "Yehuda Katz",    "Alan Johnson",    "Charles Jolley"  ]}

Page 46: 08 ajax

Conditional Rendering

Renders a portion of the template based on a condition

If the argument is falsy, the block won’t be rendered

<div class="entry">!  {{#if author}}!    <h1>{{firstName}} {{lastName}}</h1>!  {{/if}}!</div>!

Page 47: 08 ajax

Helpers

Run JS Code and put its result inside the mustache

The code is predefined as a helper

Demo: ajax/Handlebars/Demo2

Page 48: 08 ajax

Demo: Handlebars data from server

Page 49: 08 ajax

Exercise

Write a simple todo manager using Handlebars

Use a form to add a todo item

Use localStorage to save all items

Use a handlebar template to create the todo list from the local storage

Page 50: 08 ajax

Server To Client

HTTP is only one way client to server protocol

How can the server tell all clients that something new has happened ?

Page 51: 08 ajax

Server To Client

Client frequent refreshes

Web Comet

Coined as a play on Ajax

Page 52: 08 ajax

Web Sockets

Demo: http://rumpetroll.com/

Page 53: 08 ajax

Web Sockets

New Feature of HTML5

Needs a dedicated server supporting web sockets

Server-Side implementations:Socket.IO, Jetty (Java), Ruby, Python, Perl

Client Side: Native support on iPhone.

Full Solution: Socket.IO

Page 54: 08 ajax

Web Socket Arch

Socket Server(Node.js)

Application Server

ClientBrowser

MQ / DB

WEB SOCKETS HTTP

Page 55: 08 ajax

Web Sockets Paradigm

Use a dedicated node.js or other server for communicating with clients

Use a MQ server to connect node.js to your application server

juggernaut does this for you

Page 56: 08 ajax

Web Sockets Client

var connection = new WebSocket('ws://foo.org/wall');

connection.onopen = function () {! connection.send('Ping'); !};!!connection.onerror = function (error) {! console.log('WebSocket Error ' + error);!};!!connection.onmessage = function (e) {! console.log('Server: ' + e.data);!};!

Page 57: 08 ajax

Web Sockets Today

Currently, Web sockets are not widely supported

socket.io is a node.js implementation overriding this problem by providing good fallbacks

socket.io also provides a lot of extra functionality over existing web sockets

Let’s modify our code to work with socket.io

Page 58: 08 ajax

Web Sockets Client

var socket = io.connect('http://localhost:8080');

socket.on(‘connect’, function () {! connection.send('Ping'); !});!!socket.on(‘disconnect’, function () {!console.log(‘socket down’);!

};!!socket.on(‘message’, function (data) {! console.log('Server: ' + data);!};!

Page 59: 08 ajax

Demo: Echo Socket

Page 60: 08 ajax

Q & A

Page 61: 08 ajax

Thank You

Ynon Perek

[email protected]

ynonperek.com