-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy path08-AJAX.html
509 lines (496 loc) · 21 KB
/
08-AJAX.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>CMPUT 404</title>
<!-- Styling from reveal.js -->
<link rel="stylesheet" href="node_modules/reveal.js/css/reveal.css">
<link id="revealtheme" rel="stylesheet" href="">
<!-- Theme used for syntax highlighting of code -->
<link id="highlighttheme" rel="stylesheet" href="">
<!-- Custom Styling -->
<link rel="stylesheet" href="cmput404-slides.css">
<link id="404theme" rel="stylesheet" href="">
<!-- Scripts! -->
<script src="node_modules/reveal.js/lib/js/head.min.js"></script>
<script src="node_modules/reveal.js/js/reveal.js"></script>
<script src="node_modules/chai/chai.js"></script>
<script src="node_modules/fitty/dist/fitty.min.js"></script>
<script src="https://twemoji.maxcdn.com/2/twemoji.min.js"></script>
<script src="node_modules/highlightjs/highlight.pack.js"></script>
<script src="fiddler.js"></script><!-- make sure fiddler is last -->
</head>
<body>
<div class="reveal">
<div class="slides">
<!-- Anything before this will be sync'd with the other files in the directory if you run ./sync-header-footer.py *.html
HEADER --------------------------
-->
<section>
<h1>CMPUT 404</h1>
<h3>Web Applications and Architecture</h3>
<h2>Part 08: AJAX</h2>
<p>
<small>Created by <br>
<a href="http://softwareprocess.es">Abram Hindle</a>
(<a href="mailto:abram.hindle@ualberta.ca">abram.hindle@ualberta.ca</a>) <br>
and Hazel Campbell (<a href="mailto:hazel.campbell@ualberta.ca">hazel.campbell@ualberta.ca</a>).<br>
Copyright 2014-2019.
</small>
</p>
<p><small>
<button type="button" onClick="whiteStyleSheet()">White Theme</button>
<button type="button" onClick="blackStyleSheet()">Black Theme</button>
</small></p>
</section>
<section>
<h3>AJAX</h3>
<img class="stretch noborder" alt="AJAX" src="images/ajax.png">
</section>
<section>
<h3>What is AJAX?</h3>
<ul>
<li>Asynchronous JavaScript and <s>XML</s><ul>
<li>Client Side</li>
<li>Allows Javascript to make HTTP requests and use the results
without redirecting the browser.</li>
<li>Enables heavy-clients and lightweight webservices</li>
<li>Can be used to avoid presentation responsibility on the
webservice.</li>
<li>JSON is a common replacement for XML</li>
<li>Twitter.com is heavy on Ajax</li>
</ul>
</li>
</ul>
</section>
<section>
<h3>AJAX Disadvantages</h3>
<ul>
<li>You have to manage History, Back button, Bookmarks in JS</li>
<li>Security: browsers heavily restrict AJAX to prevent abuse
<ul><li>Same-Origin Policy</ul></li>
</li>
<li>Even more HTTP requests, CPU and RAM</li>
</ul>
</section>
<section>
<h3>Making Requests</h3>
<p>Use JS to make an HTTP request and get the content</p>
<ul>
<li>Old school: <var>new XMLHttpRequest()</li>
<li>Modern: <em>Fetch API</em>
<ul>
<li><var>new Request("some-url");</var>
<li>Promises!</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API">https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API</a></li>
</ul>
</li>
</ul>
</section>
<section>
<h3>Fetch API</h3>
<blockquote>
<img
class="centered"
id="fetchexample"
alt="Stop trying to make fetch happen!"
height="400">
<cite><em>Mean Girls.</em> Paramount Home Entertainment, 2005. Performed by Rachel McAdams.</cite>
</blockquote>
<button type="button" onclick="fetchExample()">Fetch!</button>
</section>
<section>
<pre><code class="html">
<blockquote>
<img height="400" class="centered" id="fetchexample"
alt="Stop trying to make fetch happen!">
<cite><em>Mean Girls.</em> Paramount Home Entertainment, 2005. Performed by Rachel McAdams.</cite>
<button type="button" onclick="fetchExample()">Fetch!</button>
</blockquote>
</pre></code>
<pre><code class="javascript">
<script>
function fetchExample() {
// https://developer.mozilla.org/en-US/docs/Web/API/Request/Request#Example 2019-02-14
var img = document.querySelector("img#fetchexample");
var request = new Request("images/fetch.gif");
var promise1 = fetch(request);
var promise2 = promise1.then(function(response) {
console.log("Got headers!");
return response.blob(); // return a promise for raw binary data
});
promise2.then(function(blob) {
console.log("Got data blob!");
var objectURL = URL.createObjectURL(blob);
img.src = objectURL;
});
}
// Note in the DOM the img's src= attribute after running!</pre></code>
</script>
</code></pre>
</section>
<section>
<h3>Promises, Promises</h3>
<pre><code class="javascript">
<script>
function makeAPromise(data) {
return new Promise((resolve, reject) => {
resolve(data);
});
}
function promiseExample() {
// .then returns a NEW promise
var promise1 = makeAPromise("X");
var promise2 = promise1.then((data2) => {
// inner function gets called after the promise is resolved
alert("data2: " + data2);
return "Y";
});
// .then calls its argument with the return value of the
// previous promises's callback function
var promise3 = promise2.then((data3) => {
alert("data3: " + data3);
});
}
</script>
</pre></code>
<button type="button" onclick="promiseExample()">promiseExample()</button>
</section>
<section style="font-size: 85%">
<h3>Promise dot-chaining</h3>
<pre><code class="javascript">
var request = new Request("images/fetch.gif");
var promise1 = fetch(request);
var promise2 = promise1.then(function(response) {
console.log("Got headers!");
return response.blob(); // return a promise for raw binary data
});
promise2.then(function(blob) {
console.log("Got data blob!");
var objectURL = URL.createObjectURL(blob);
img.src = objectURL;
});
}
</pre></code>
<p>is the same as</p>
<pre><code class="javascript">
var request = new Request("images/fetch.gif");
fetch(request).then(function(response) {
console.log("Got headers!");
return response.blob(); // return a promise for raw binary data
}).then(function(blob) {
console.log("Got data blob!");
var objectURL = URL.createObjectURL(blob);
img.src = objectURL;
});
</pre></code>
</section>
<section>
<h3>Fetching JSON</h3>
<p>Let's make a generic JSON GET function</p>
<pre><code class="javascript">
<script>
function fetchJSON(url) {
var request = new Request(url);
return fetch(request).then((response) => {
if (response.status === 200) { // OK
return response.json(); // return a Promise
} else {
alert("Something went wrong: " + response.status);
}
});
}
</script>
</code></pre>
</section>
<section style="font-size: 75%">
<h3>Do something with the JSON</h3>
<pre><code class="javascript">
<script>
var getterID; // global
function startGetting() {
getterID = window.setInterval(() => { // callback
var now = new Date();
var s = 1 + (now.getSeconds() % 4); // remainder
var url = s + ".json" // 1.json 2.json 3.json...
fetchJSON(url).then((json) => { // another callback
console.log(json); // browser turned the JSON into an object
text = json.message; // it has properties
document.querySelector("#ajaxy").innerText = text;
});
}, 1000); // 1 second or 1000ms
}
function stopGetting() {
window.clearInterval(getterID);
}
</script>
</code></pre>
<pre><code class="html">
<button type="button" onclick="startGetting()">Start Getting</button>
<button type="button" onclick="stopGetting()">Stop Getting</button>
<blockquote id="ajaxy"></blockquote>
</code></pre>
<button type="button" onclick="startGetting()">Start Getting</button><button type="button" onclick="stopGetting()">Stop Getting</button>
<blockquote id="ajaxy"></blockquote>
</section>
<section>
<h3>Timers</h3>
<ul>
<li><var>window.setInterval</var> lets you run a function every so many milliseconds.</li>
<li><var>window.setTimeout</var> lets you run a function once after so many milliseconds.</li>
</ul>
</section>
<section>
<h3>JSON</h3>
<ul>
<li>JavaScript Object Notation</li>
<li>Strict subset of JavaScript</li>
<li><a href="http://json.org/">http://json.org/</a>
<li><var>JSON.parse</var> parses JSON text into an Object</li>
<li><var>JSON.stringify</var> turns an Object into JSON text</li>
</ul>
</section>
<section>
<pre><code class="javascript">
<script>
function stringifyExample() {
var obj = { "food":"hotdog",
"condiments":["ketchup","mustard","cheese"],
"sausage":"weiner"
};
document.querySelector("#hotdog").value =
JSON.stringify(obj, null, " "); // pretty print
}
function parseExample() {
text = document.querySelector("#hotdog").value;
var newObj = JSON.parse(text);
document.querySelector("#sausage").innerText = newObj.sausage;
}
</script>
</code></pre>
<button type="button" onclick="stringifyExample()">stringifyExample()</button>
<button type="parse" onclick="parseExample()">parseExample()</button><br>
<textarea id="hotdog" rows="10" cols="80"></textarea>
<blockquote id="sausage"></blockquote>
</section>
<section>
<h3>Design With AJAX</h3>
<p>Design Suggestions:</p>
<ul>
<li><a href="http://softwareas.com/ajax-patterns">Minimize AJAX requests and traffic</a>
</li>
<li>Don't hook into every event, <a href="http://serversideguy.blogspot.ca/2004/12/google-suggest-dissected.html">use timeouts?</a>
</li>
<li>Use to ease page state transitions
</li>
</ul>
</section>
<section>
<p>What are your events?</p>
<ul>
<li>Per user input?</li>
<li>Per user commit?</li>
<li>Time based?</li>
<li>Per Server action?<ul>
<li>Polling?</li>
</ul>
</li>
<li>Data?</li>
<li>Content oriented?</li>
<li>Messages?</li>
<li>Multimedia?</li>
<li>Read-based <a href="http://www.reddit.com/r/programming/">(reddit)</a></li>
</ul>
</section>
<section>
<h3>AJAX Observer Pattern</h3>
<ul>
<li>Observer pattern is where an observable keeps a collection of observers (listeners) and notifies those observers if anything changed by sending an update message.</li>
<li>This works great with AJAX if the observable is held client side in a browser and the observer is client side in the browser! Go ahead!</li>
</ul>
</section>
<section>
<h4>AJAX Observer Pattern</h4>
<img class="centered noborder" src="images/observer.svg" alt="Observer UML Diagram">
</section>
<section>
<h4>AJAX Observer Pattern</h4>
<ul>
<li>Still works well with observable in browser and the observers server-side, the client simply notifies via the server's observers whenever an update occurs (but it should also communicate some lightweight state).</li>
<li>Due to the lack of a client-side HTTP server it is problematic to do the observer pattern with client side observers.</li>
</ul>
</section>
<section>
<h3>Observing the Server</h3>
<ul>
<li>HTTP is stateless, so a client needs to communicate somehow all of
the objects it is observing. <ul>
<li>Perhaps a serverside Observer proxy that stores observables for a
client</li>
</ul>
</li>
<li>Clients need to poll the server to check if there are updates. For
the observer pattern to work this polling should allow the server to
send update commands.</li>
<li>Due to bandwidth concerns and latency concerns, an update from the
server should probably include relevant data </li>
</ul>
</section>
<section>
<h4>Observing the Server</h4>
<ul>
<li>Fighting against:<ul>
<li>Latency</li>
<li>Bandwidth</li>
<li>Lack of communication channels</li>
<li>Lack of ability to push messages to a client</li>
<li>Polling</li>
<li>Timer smashing</li>
</ul>
</li>
</ul>
</section>
<section>
<h4>Observing the Server</h4>
<p>Solutions?</p>
<ul>
<li>Polling: the most common</li>
<li>Push API: not supported in all browsers</li>
<li>Comet "long polling": difficult server-side support</li>
<li>Websockets: need to make a websocket server</li>
</ul>
</section>
<section>
<h3>Polling the Server</h3>
<ul>
<li>Don't send too many requests
</li>
<li>Batch (bundle together) requests to the server</li>
<li>Minimize the number of timers and the frequency of timers
<ul>
<li>E.g. if drawing, a user doesn't need more than 30FPS!</li>
</ul>
<li>Don't make requests until the previous request finished...</li>
<li>Don't make requests you don't have to</li>
</ul>
</section>
<section>
<h3>AJAX Resources</h3>
<ul>
<li><a href="http://softwareas.com/ajax-patterns">AJAX Patterns: Design Patterns for AJAX Usability</a> --
Michael Mahemoff<ul>
<li><a href="http://ajaxpatterns.org/">AJAX Pattern</a></li>
<li><a href="http://proquest.safaribooksonline.com/book/web-development/ajax/0596101805">O'Reilly Book</a></li>
</ul>
</li>
<li><a href="http://serversideguy.blogspot.ca/2004/12/google-suggest-dissected.html">Google Dissected</a></li>
<li><a href="https://www.youtube.com/watch?v=sZqpmRlOjU8">Ajax Frameworks and Design Patterns
Survey</a> (video)</li>
</ul>
</section>
<section>
<h3>More JavaScript: <var>async</var> and <var>await</var></h3>
<ul>
<li><var>async</var> functions
<ul>
<li>Return a promise!</li>
</ul>
</li>
<li><var>await</var> in async functions
<ul>
<li>blocks code execution (stop and wait for the promise to resolve)</li>
</ul>
</li>
</ul>
</section>
<section style="font-size: 75%">
<h3>Async Await Example</h3>
<pre><code class="javascript">
<script>
var getterID; // global
async function get2() {
var now = new Date();
var s = 1 + (now.getSeconds() % 4); // remainder
var url = s + ".json" // 1.json 2.json 3.json...
var json = await fetchJSON(url);
console.log(json); // browser turned the JSON into an object
var text = json.message; // it has properties
document.querySelector("#ajaxy2").innerText = text;
}
function startGetting2() {
getterID2 = window.setInterval(get2, 1000); // 1 second or 1000ms
}
function stopGetting2() {
window.clearInterval(getterID2);
}
</script>
</code></pre>
<pre><code class="html">
<button type="button" onclick="startGetting2()">Start Getting</button>
<button type="button" onclick="stopGetting2()">Stop Getting</button>
<blockquote id="ajaxy2"></blockquote>
</code></pre>
<button type="button" onclick="startGetting2()">Start Getting</button><button type="button" onclick="stopGetting2()">Stop Getting</button>
<blockquote id="ajaxy2"></blockquote>
</section>
<section>
<h3>async/await Disadvantages</h3>
<ul>
<li>Execution stops at await, instead of continuing in parallel
<ul>
<li>In threads if the browser supports it</li>
</ul>
</li>
<li>With <var>.then(...)</var> in a loop, the loop completes instantly
and each callback function can run in parallel as soon as its ready</li>
<li>With <var>await</var> in a loop, the loop will keep stopping each time
it gets to the await</li>
</ul>
</section>
<section>
<h3>Observer Example</h3>
<ul>
<li>in <var>examples/ObserverExampleAJAX</var>
</li>
<li><a href="https://github.com/uofa-cmput404/cmput404-slides/tree/master/examples/ObserverExampleAJAX">https://github.com/uofa-cmput404/cmput404-slides/tree/master/examples/ObserverExampleAJAX</a></li>
</ul>
</section>
<!-- Anything after this will be sync'd with the other files in the directory if you run ./sync-header-footer.py *.html
FOOTER --------------------------
-->
<section style="font-size: 90%">
<h4>License</h4>
<p>Copyright 2014 ⓒ Abram Hindle</p>
<p>Copyright 2019 ⓒ Hazel Victoria Campbell and contributors</p>
<a rel="license" href="http://creativecommons.org/licenses/by-sa/4.0/"><img alt="Creative Commons Licence" style="border-width:0" src="https://i.creativecommons.org/l/by-sa/4.0/88x31.png" /></a><br />The textual components and original images of this slide deck are
placed under the Creative Commons is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-sa/4.0/">Creative Commons Attribution-ShareAlike 4.0 International License</a>.
</p>
<p>Other images used under fair use and copyright their copyright holders.</p>
</section>
<section>
<h4>License</h4>
The source code to this slide deck is:
<pre><code class="plaintext">
Copyright (C) 2018 Hakim El Hattab, http://hakim.se, and reveal.js contributors
Copyright (C) 2019 Hazel Victoria Campbell, Abram Hindle and contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
</code></pre>
</section>
</div>
</div>
</body>
</html>