AJAX +
Intro to client-‐side templa5ng
6470 IAP 2014
This week…
• Today – AJAX & Handlebars – Facebook and Parse
• Tomorrow – Something fun TBD – Appian
• Thursday – Vecna – Yext
• All in 34-‐101, 11AM
So far…
• Server-‐side technologies – PHP, Rails, node.js, etc. – Handles request from browser
So far…
• Server-‐side technologies – PHP, Rails, node.js, etc. – Handles request from browser
• Client-‐side technologies – HTML, CSS, Javascript – Interpreted on browser
So far…
• Server-‐side technologies – PHP, Rails, node.js, etc. – Handles request from browser
• Client-‐side technologies – HTML, CSS, Javascript – Interpreted on browser
generates
CLIENT
SERVER
Request: GET mysite.com/id/1
Response: <html>…</html>
CLIENT
SERVER
Request: GET mysite.com/id/1
Response: <html>…</html>
Page refresh
No page refresh?
CLIENT
SERVER
Request: GET mysite.com/id/1
Response: <html>…</html>
Page refresh
AJAX Asynchronous Javascript and XML
(but not really XML)
Asynchronous? setTimeout(function() {!
!alert(‘hello’);!}, 3000);!!!helloServer = http.createServer(function (req, res){ !
!res.writeHead(200, {'Content-Type': ! !'text/plain'}); !!res.end('Hello World'); !
}).listen(8000)!!!
Listeners and callbacks
• When something happens (listen for it), execute the callback func*on
$(‘#element’).click(function() { … });!
Listeners and callbacks
• Make the request • When something happens (listen for it), execute the callback func*on
• Con5nue to do whatever else
Listeners and callbacks
• Make the request • When something happens (listen for it), execute the callback func*on
• Con5nue to do whatever else
the server’s response comes back
function loadXMLDoc() {! var xmlhttp;!! if (window.XMLHttpRequest) {! // code for IE7+, Firefox, Chrome, Opera, Safari! xmlhttp = new XMLHttpRequest();! } else {! // code for IE6, IE5! xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");! }!! xmlhttp.onreadystatechange = function() {! if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {! document.getElementById("myDiv").innerHTML = xmlhttp.responseText;! }! } ! !// this is the callback function!
! xmlhttp.open("GET", "ajax_info.txt", true);! xmlhttp.send();!}!
AJAX without jQuery
• Lots of code • Not cross-‐browser compa5ble!
jQuery $.get and $.post $.get(url, {param1: val1 …}, function(data){!
!// callback function!}, datatype);!!!$.post(url, {param1: val1 …}, function(data){!
!// callback function!}, datatype);!
1. Send the request -‐ immediately when $.get or $.post is called
2. When response comes back
-‐ execute callback func5on -‐ datatype parameter: xml, html, json, script, text
The AJAX response
• Don’t need to send huge HTML files around
• JSON (most common) – {‘name’ : ‘Charles’, ‘email’ : ‘6.470-‐[email protected]’} – Interpreted into Javascript object
AJAX server-‐side
• Response is json-‐encoded object or array
• PHP: echo json_encode($obj)!!
• Rails – render json: @obj!– render { key1 : val1 …}.to_json!– Render different formats in same controller
Example – a simple messageboard
• hqps://github.com/kongming92/6470_ajax
• hqp://cliu2014.scripts.mit.edu/message/
Handlebars.js
What is Handlebars?
• Client side templa5ng
• An HTML “template” <li>{{name}}: {{message}}</li>!
• Fill in the placeholders {name: ‘Charles’, message: ‘hello there’}!
Why Handlebars?
From earlier example… !function(data) {!
!if (data.success) {!! !var item = $('<li />').html('<span ! ! !class="name">' + data.name + ! ! !'</span>: ' + data.message + ! ! !'</li>');!! !$('#messages').prepend(item);!!!}!
}!
Why Handlebars?
• HTML strings in Javascript à messy JS – Even worse with nested elements
• Bad code: data and its presenta5on are intermingled
Using Handlebars
• Add it to your Javascript – Download Handlebars.js file, include as a script <script src=“handlebars-v1.3.0.js” type=“text/javascript></script>!
Using Handlebars
• Compile a template – returns a func*on !var template = Handlebars.compile($(‘#template’).html());!
Using Handlebars
• Run the template on data !var data = {name: ‘Charles’, message: ‘Hello there’};!!template(data); // returns HTML with data inserted!!
Handlebars templates
• Add it as a script in your HTML!<script id="msg-template" type="text/x-handlebars-template">!!<li>{{name}}: {{message}}</li>!
</script>!
• Get the template using jQuery
$(‘#msg-template’).html();!
Some built-‐in helpers
• The each helper: runs on each element of an array: var data = { people: [!! ! ! !{name : ‘person1’},!! ! ! !{name : ‘person2’} …!! ! !]!! !};!
!{{#each people}}!!<li>{{name}}</li> !!
{{/each}}!
Some built-‐in helpers
• The if helper – Output if value is not null/false/0/undefined – Can’t use condi5onals – only test a single variable’s value
{{#if arr.length}}!!…output…!
{{else}}!!…else output…!
{{/if}}!
Some built-‐in helpers
• The unless helper – Opposite of if
Par5als
• Make a template out of other templates • In the template!
!{{#each messages}}!! !{{> message}}!!{{/each}}!
• In the Javascript Handlebars.registerPartial(“message”, $(‘#msg-template’).html());!
Example
• hqps://github.com/kongming92/6470_hbs
• hqp://cliu2014.scripts.mit.edu/message_hbs/
More cool things
• Custom helpers
• Precompiling – templates in their own files
• “More black magic” – client side MVC – Backbone.js – Ember.js – Angular.js
Top Related