This repository has been archived by the owner on Jan 11, 2019. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy path06.ajax.html
executable file
·1336 lines (1227 loc) · 47.7 KB
/
06.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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Web & Mobile Development — 06.Ajax</title>
<meta name="description" content="Web & Mobile Development — 06.Ajax">
<meta name="author" content="Bram(us) Van Damme - ikdoeict.be">
<link href='http://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="css/reset.css">
<link rel="stylesheet" href="css/main.css" media="screen">
<link rel="stylesheet" href="css/print.css" media="print">
<!-- <link rel="stylesheet" href="assets/06/examples.css"> -->
<link rel="stylesheet" href="lib/zenburn.css">
</head>
<body>
<div id="reveal">
<!-- Any section element inside of this container is displayed as a slide -->
<div class="slides">
<!-- 0 : Title -->
<section>
<section>
<h3 class="inverted">Web & Mobile Development <small>JLW288</small></h3>
<h1>06.Ajax</h1>
<footer>
<em><a href="http://www.ikdoeict.be/">ikdoeict.be</a> — <a href="mailto:[email protected]">[email protected]</a></em>
</footer>
<script>
// Delicously hacky. Look away.
if(navigator.userAgent.match(/(iPhone|iPad|iPod|Android)/i))
document.write('<p style="color: rgba(0,0,0,0.3); text-shadow: none;">('+'Tap to navigate'+')</p>');
</script>
</section>
</section>
<!-- 1 : Ajax Intro -->
<section>
<section>
<p><img src="assets/06/ajax.jpg" alt="" title="" height="496" width="495" /></p>
</section>
<section>
<h2>Ajax?</h2>
<ul>
<li class="fragment">
Acronym: Asynchronous JavaScript and XML
<ul>
<li>Term <a href="http://www.adaptivepath.com/ideas/ajax-new-approach-web-applications">coined in 2005</a> by Jesse James Garret</li>
<li>Technology pre-dated 2005 though</li>
</ul>
</li>
<li class="fragment">
In Short
<ul>
<li>Ajax allows you to do requests to a web server without ever leaving the webpage</li>
</ul>
</li>
<li class="fragment">
Example
<ul>
<li>Click a link in the navigation of a webpage and see the content get updated dynamically</li>
</ul>
</li>
</ul>
</section>
<section>
<h2>XMLHttpRequest</h2>
<ul>
<li class="fragment">
At the core of Ajax sits a JavaScript API named <code>XMLHttpRequest</code> (XHR)
<ul>
<li class="fragment">It allows you to do a request to a web server</li>
<li class="fragment">Calls can be made synchronously and asynchronously</li>
</ul>
</li>
<li class="fragment">
Other parts of Ajax are DOM Manipulations and XML
<ul>
<li class="fragment">The data (text) returned by the server is XML-formatted (*)</li>
</ul>
</li>
</ul>
<footer class="fragment"><em>(* by now other formats are more popular)</em></footer>
</section>
<section>
<h2>Example</h2>
<ul>
<li class="fragment">
Synchronous example
<pre class="bigger"><code class="language-javascript" contenteditable>xhr = new XMLHttpRequest();
xhr.open('GET', 'assets/06/examples/xml.php', false);
xhr.send(null);
alert('I am outputted once the call has finished loading (5s delay)');
alert(xhr.responseText);</code></pre>
</li>
<li class="fragment">
Asynchronous example
<pre class="bigger"><code class="language-javascript" contenteditable>xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
alert(xhr.responseText);
}
};
xhr.open('GET', 'assets/06/examples/xml.php', true);
xhr.send(null);
alert('I am outputted immediately (no delay)');</code></pre>
</li>
</ul>
<footer class="fragment">The asynchronous way is preferred</footer>
</section>
<section>
<h2>Advantages & Disadvantages</h2>
<ul>
<li class="fragment">
Advantages
<ul>
<li class="fragment">No reloads</li>
<li class="fragment">Less bandwidth used</li>
<li class="fragment">Perceived speed by user</li>
</ul>
</li>
<li class="fragment">
Disadvantages
<ul>
<li class="fragment">
URLs “broken”
<ul>
<li>No browser history</li>
<li>No back/forward</li>
<li>No proper bookmarking</li>
</ul>
</li>
<li class="fragment">
Search Engines don't index content injected afterwards
</li>
<li class="fragment">
Requires a change in programming attitude
</li>
</ul>
</li>
</ul>
</section>
<section>
<h2>XHR History</h2>
<ul>
<li class="fragment">
XHR's predecessor <code>IXMLHTTPRequest</code> invented by Microsoft
<ul>
<li>Shipped with IE5 (1999!), as part of the <code>MSXML</code> Library</li>
<li>Available in JS via ActiveX</li>
</ul>
</li>
<li class="fragment">By 2002 Mozilla had a fully working clone named <code>XMLHttpRequest</code> in Gecko</li>
<li class="fragment">
Other browsers also followed
<ul>
<li>Safari (2004)</li>
<li>Opera (2005)</li>
<li>IE7 (2006)</li>
</ul>
</li>
<li class="fragment">
W3C started working on a standard in 2008
</li>
</ul>
</section>
<section>
<h2>XHR in IE5/IE6</h2>
<ul>
<li class="fragment">
Define your own <code>XMLHttpRequest</code> Object and return the ActiveX Object
<pre class="bigger"><code class="language-javascript">if (typeof XMLHttpRequest == "undefined")
XMLHttpRequest = function() {
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); }
catch (e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); }
catch (e) {}
try { return new ActiveXObject("Microsoft.XMLHTTP"); }
catch (e) {}
throw new Error("This browser does not support XMLHttpRequest");
};
xhr = new XMLHttpRequest();
// rest of your code ....</code></pre>
</li>
</ul>
</section>
<section>
<h2>Same Origin Policy</h2>
<ul>
<li class="fragment">
For security reasons, it's only possible to make requests to the same url that serves the page making the request
<ul>
<li class="fragment">It's not possible to call <code>http://api.ikdoeict.be/</code> from <code>http://www.ikdoeict.be/</code></li>
</ul>
</li>
<li class="fragment">
There are ways to circumvent this though <em>(see further)</em>
</li>
</ul>
</section>
</section>
<!-- 2 : Return Types -->
<section>
<section>
<h2>Ajax Return Types</h2>
<p><img src="assets/06/futurama_nixon.jpg" alt="" title="" height="309" width="446" /></p>
<q>I've sent you each 300 buckeroos. In the form of a tricky Dick fun bill. Knock yourselves out! </q>
</section>
<section>
<h2>Ajax Return Types</h2>
<ul>
<li class="fragment">Everything returned by Ajax is textual data</li>
<li class="fragment">
Doesn't mean it's plaintext though
<ul>
<li class="fragment">XML</li>
<li class="fragment">HTML</li>
<li class="fragment">JavaScript</li>
<li class="fragment">JSON</li>
</ul>
</li>
</ul>
</section>
<section>
<h2>XML</h2>
<ul>
<li class="fragment">
Initial usage mostly used XML
<ul>
<li class="fragment">Server must send <code>Content-Type: text/xml</code> header, XHR will <em>automagically</em> parse the returned data as XML</li>
</ul>
</li>
<li class="fragment">
Once data is parsed by XHR, walk through the XML nodes tree to get fetch the values you need
<ul>
<li class="fragment">Most of the time a cumbersome work though</li>
</ul>
</li>
<li class="fragment">
Once XML is parsed, build an HTML string with the data and inject the HTML blog into your document.
</li>
</ul>
</section>
<section>
<h2>XML Example (1)</h2>
<ul>
<li class="fragment">
Data returned
<pre class="bigger"><code class="language-xml"><?xml version="1.0" encoding="UTF-8"?>
<sample>
<course>WMD</course>
<lecturers>
<lecturer>Bramus Van Damme</lecturer>
<lecturer>Davy De Winne</lecturer>
</lecturers>
</sample></code></pre>
</li>
</ul>
</section>
<section>
<h2>XML Example (2)</h2>
<ul>
<li class="fragment">
JS Implementation
<pre class="bigger"><code class="language-javascript" contenteditable>xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var xml = xhr.responseXML,
courseName = xml.getElementsByTagName('course')[0].firstChild.nodeValue,
lecturersXml = xml.getElementsByTagName('lecturer'),
lecturers = [];
console.log(xml);
for (var i = 0, len = lecturersXml.length; i < len; i++) {
lecturers.push(lecturersXml[i].firstChild.nodeValue);
}
alert('<p>' + courseName + ' is taught by ' + lecturers.join(' & ') + '</p>');
}
};
xhr.open('GET', 'assets/06/examples/xml-nodelay.php', true);
xhr.send(null);</code></pre>
</li>
</ul>
</section>
<section>
<h2>HTML</h2>
<ul>
<li class="fragment">
Why not let the server prepare a blob of HTML instead of building it after having parse the XML?
<ul>
<li class="fragment">
Data returned
<pre class="bigger"><code class="language-html dontrun"><p>WMD is taught by Davy De Winne &amp; Bramus Van Damme</p></code></pre>
</li>
<li class="fragment">
JS Implementation
<pre class="bigger"><code class="language-javascript" contenteditable>xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var html = xhr.responseText;
alert(html);
}
};
xhr.open('GET', 'assets/06/examples/html.php', true);
xhr.send(null);</code></pre>
</li>
</ul>
</li>
</ul>
</section>
<section>
<h2>JavaScript</h2>
<ul>
<li class="fragment">
Load in a tad of JavaScript, and then <code>eval()</code> it.
<ul>
<li class="fragment">
Data returned
<pre class="bigger"><code class="language-js dontrun">alert('<p>WMD is taught by Davy De Winne &amp; Bramus Van Damme</p>');</code></pre>
</li>
<li class="fragment">
JS Implementation
<pre class="bigger"><code class="language-javascript" contenteditable>xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var js = xhr.responseText;
eval(js);
}
};
xhr.open('GET', 'assets/06/examples/js.php', true);
xhr.send(null);</code></pre>
</li>
</ul>
</li>
<li class="fragment">
Beware when using <code>eval()</code> though: <a href="http://xkr.us/js/eval"><code>eval()</code> is evil</a>.
<ul>
<li class="fragment">But not always: In this case, it is allowed</li>
</ul>
</li>
</ul>
</section>
<section>
<h2>JavaScript: External Files</h2>
<ul>
<li class="fragment">
No need for Ajax if you need to include an external file
<pre class="bigger"><code class="language-javascript dontrun">var head = document.getElementsByTagName("head")[0],
script = document.createElement('script');
script.type = 'text/javascript';
script.src = "/path/to/your/file.js";
head.appendChild(script);</code></pre>
</li>
<li class="fragment">
Does give problems though, as you cannot know when the script has finished loading
<ul>
<li class="fragment">In that case you will need XHR, or — even better — a specific script loader such as <a href="http://requirejs.org/">RequireJS</a>
</ul>
</li>
</ul>
</section>
<section>
<h2>JSON</h2>
<ul>
<li class="fragment">
JSON = JavaScript Object Notation
<ul>
<li class="fragment">In Short: JSON a JavaScript Object Literal, represented as a string</li>
<li class="fragment">Described by Douglas Crockford in 2006 (<a href="http://tools.ietf.org/html/rfc4627">RFC 4627</a>)</li>
</ul>
</li>
<li class="fragment">
Format Example
<pre class="bigger"><code class="language-javascript dontrun">{
"course": "WMD",
"lecturers": [
{
"id": 1,
"name": "Davy De Winne"
},
{
"id": 2,
"name": "Bramus Van Damme"
}
]
}</code></pre>
</li>
</ul>
</section>
<section>
<h2>JSON Format</h2>
<ul>
<li class="fragment">
JSON = One big Object with keys and values
<div style="text-align: center; margin-top: 10px;">
<figure>
<img src="assets/06/json_object.gif" alt="" title="" height="113" width="598" style="background: #FFF;" />
<figcaption>Figure by <a href="http://json.org/">json.org</a></figcaption>
</figure>
</div>
<ul>
<li class="fragment">Multiple key-value pairs: comma-delimited</li>
<li class="fragment">Keys are of the type <code>string</code> <em>(double quotes required!)</em></li>
<li class="fragment">Values are <code>string</code>, <code>number</code>, <code>Object</code>, <code>Array</code>, <code>boolean</code> or <code>null</code></li>
</ul>
</li>
</ul>
</section>
<section>
<h2>JSON Example</h2>
<ul>
<li class="fragment">
Example
<pre class="bigger"><code class="language-javascript" contenteditable>xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var json = JSON.parse(xhr.responseText), lecturers =[];
for (var i = 0, len = json.lecturers.length; i < len; i++) {
lecturers.push(json.lecturers[i].name);
}
alert('<p>' + json.course + ' is taught by ' + lecturers.join(' & ') + '</p>');
}
};
xhr.open('GET', 'assets/06/examples/json.php', true);
xhr.send(null);</code></pre>
<ul>
<li class="fragment">
XHR doesn't parse the string to JSON <em>automagically</em>, you will need to manually parse it using <code>JSON.parse()</code> (reverse: <code>JSON.stringify()</code>)
<ul>
<li class="fragment">Older browsers that don't support <code>JSON.parse()</code> require <a href="https://github.com/douglascrockford/JSON-js">a library</a> to do the parsing.</li>
</ul>
</li>
</ul>
</li>
</ul>
</section>
<section>
<h2>Sidenote: JSON in PHP</h2>
<ul>
<li class="fragment">
Since PHP 5.2, JSON in PHP is really easy
<ul>
<li class="fragment">Encode an Array to JSON with <code>json_encode</code><small><a href="http://be.php.net/json_encode">⚑</a></small></li>
<li class="fragment">Decode JSON String into an Object or Associative Array with <code>json_decode</code><small><a href="http://be.php.net/json_decode">⚑</a></small></li>
</ul>
</li>
<li class="fragment">
Send a JSON header back with this header
<ul>
<li class="fragment"><code>Content-Type: application/json</code></li>
</ul>
</li>
</ul>
</section>
<section>
<h2>What to choose?</h2>
<ul>
<li class="fragment">
JSON FTW!
<ul>
<li class="fragment">Easier to work with (both JS & PHP)</li>
<li class="fragment">Smaller than XML</li>
<li class="fragment">Very readable</li>
<li class="fragment">All modern webapp API's output JSON</li>
</ul>
</li>
<blockquote class="fragment" style="text-align: center; margin-top: 1em;">Ajax: X is for JSON</blockquote>
</ul>
</section>
</section>
<!-- 3 : Ajax in jQuery -->
<section>
<section>
<h2>Ajax in jQuery</h2>
<p><img src="assets/06/futurama_money.jpg" alt="" title="" height="252" width="446" /></p>
<q>Shut up and take my money!</q>
</section>
<section>
<h2>$.ajax()</h2>
<ul>
<li class="fragment">
The core function jQuery to make Ajax calls is <code>$.ajax()</code>
<ul>
<li class="fragment">Pass in an object to tell jQuery what to call and how</li>
</ul>
</li>
<li class="fragment">
Example
<pre class="bigger"><code class="language-javascript dontrun" data-overlay-example="assets/06/examples/jquery.ajax.html">jQuery(document).ready(function($) {
$.ajax({
url: 'json.php',
type: 'get',
dataType: 'json',
success: function(data, textStatus, jqXHR) {
var lecturers = [];
for (var i = 0, len = data.lecturers.length; i < len; i++) {
lecturers.push(data.lecturers[i].name);
}
$('#output').html('<p>' + data.course + ' is taught by ' + lecturers.join(' & ') + '</p>');
},
error : function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
});
});</code></pre>
</li>
</ul>
</section>
<section>
<h2>$.ajax() Parameters (1)</h2>
<ul>
<li class="fragment">
Five basic parameters
<ul>
<li class="fragment"><code>url</code>: A string containing the URL to which the request is sent.</li>
<li class="fragment"><code>success</code>: A function to be called if the request succeeds.</li>
<li class="fragment"><code>error</code>: A function to be called if the request fails.</li>
<li class="fragment"><code>type</code>: Type of request to make (<code>POST</code> or <code>GET</code>). Defaults to <code>GET</code></li>
<li class="fragment"><code>dataType</code>: Type of data you're expecting back from the server.
<ul>
<li><code>xml</code></li>
<li><code>html</code></li>
<li><code>script</code> — Will be interpreted automatically. Only via <code>GET</code>.</li>
<li><code>json</code> — Will be parsed automatically.</li>
<li><code>jsonp</code></li>
<li><code>text</code></li>
<li>(empty → jQuery will guess the type)</li>
</ul>
</li>
</ul>
</li>
</ul>
</section>
<section>
<h2>$.ajax() Parameters (1)</h2>
<ul>
<li class="fragment">
Other interesting parameters
<ul>
<li class="fragment"><code>async</code>: Set to <code>false</code> if you need synchronous requests</li>
<li class="fragment"><code>data</code>: Extra data to be sent to the server (eg. form data)</li>
<li class="fragment"><code>headers</code>: Extra headers to be sent along with the request</li>
<li class="fragment"><code>username</code> & <code>password</code>: HTTP Authentication</li>
</ul>
</li>
<li class="fragment">
Full list of parameters to be found in the <a href="http://api.jquery.com/jQuery.ajax/">jQuery API</a>
</li>
</ul>
</section>
<section>
<h2>Sending data</h2>
<ul>
<li class="fragment">
Possible via <code>data</code> parameter
<ul>
<li class="fragment">
Format is a querystring: <code>key=value&key=value&key=value</code>
</li>
</ul>
</li>
<li class="fragment">
Manually building a querystring
<pre class="bigger"><code class="language-javascript dontrun">var values = [
'firstname=' + encodeURIComponent($('#firstname').val()),
'lastname=' + encodeURIComponent($('#lastname').val())
];
var queryString = values.join('&');</code></pre>
</li>
<li class="fragment">
Automatic version: <code>$.fn.serialize()</code>
<pre class="bigger"><code class="language-javascript dontrun">var queryString = $('#signupform').serialize();</code></pre>
</li>
<li class="fragment">
Also possible: an Object
<pre class="bigger"><code class="language-javascript dontrun">{key : "value"}</code></pre>
</li>
</ul>
</section>
<section>
<h2>$.ajax() alternative syntax</h2>
<ul>
<li class="fragment">
jQuery1.5 introduced <a href="http://api.jquery.com/category/deferred-object/">deferreds</a> which allow this:
<pre class="bigger"><code class="language-javascript dontrun" data-overlay-example="assets/06/examples/jquery.ajax2.html">jQuery(document).ready(function($) {
$.ajax({
url: 'json.php',
type: 'get',
dataType: 'json'
}).success(function(data, textStatus, jqXHR) {
var lecturers = [];
for (var i = 0, len = data.lecturers.length; i < len; i++) {
lecturers.push(data.lecturers[i].name);
}
$('#output').html('<p>' + data.course + ' is taught by ' + lecturers.join(' & ') + '</p>');
}).error(function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
});
});</code></pre>
<ul>
<li class="fragment">Instead of passsing <code>succes</code> and <code>error</code> functions in the call, you hook them onto the request</li>
</ul>
</li>
</ul>
</section>
<section>
<h2>Sidenote: Deferreds</h2>
<ul>
<li class="fragment">
Deferreds are awesome!
<ul>
<li class="fragment">When creating the ajax call, you get back a <strong>promise</strong></li>
<li class="fragment">The <code>success</code> and <code>error</code> functions are bound to the promise</li>
<li class="fragment">When the ajax call is completed, the promise is <strong>resolved</strong> and the attached functions are executed</li>
</ul>
</li>
<li class="fragment">You can create your own deferreds in jQuery</li>
<li class="fragment">jQuery has an easy <code>$.when(<em>deferred</em>).then(<em>function</em>)</code> shorthand<small><a href="http://api.jquery.com/jQuery.when/">⚑</a></small></li>
</ul>
</section>
<section>
<h2>Basic Shorthands</h2>
<ul>
<li class="fragment">
jQuery offers shorthands to make <code>GET</code> and <code>POST</code> requests
<ul>
<li class="fragment"><a href="http://api.jquery.com/jQuery.get/">$.get()</a></li>
<li class="fragment"><a href="http://api.jquery.com/jQuery.post/">$.post()</a></li>
</ul>
</li>
<li class="fragment">Internally these calls are routed to <code>$.ajax()</code></li>
<li class="fragment">Code is more concise, yet allows less configuration</li>
</ul>
</section>
<section>
<h2>Basic Shorthands: $.get()</h2>
<ul>
<li class="fragment">
Example
<pre class="bigger"><code class="language-javascript dontrun" data-overlay-example="assets/06/examples/jquery.get.html">jQuery(document).ready(function($) {
$.get('json.php', function(data, textStatus, jqXHR) {
var lecturers = [];
for (var i = 0, len = data.lecturers.length; i < len; i++) {
lecturers.push(data.lecturers[i].name);
}
$('#output').html('<p>' + data.course + ' is taught by ' + lecturers.join(' & ') + '</p>');
}, 'json');
});</code></pre>
</li>
<li class="fragment">
Possible to pass in extra data
<pre class="bigger"><code class="language-javascript dontrun">jQuery(document).ready(function($) {
$.get('json.php', { key: "value" }, function(data, textStatus, jqXHR) {
// ...
}, 'json');
});</code></pre>
</li>
</ul>
</section>
<section>
<h2>Basic Shorthands: $.post()</h2>
<ul>
<li class="fragment">
Same syntax as <code>$.get()</code>
<pre class="bigger"><code class="language-javascript dontrun">jQuery(document).ready(function($) {
$.post('json.php', { key: "value" }, function(data, textStatus, jqXHR) {
// ...
}, 'json');
});</code></pre>
</li>
</ul>
</section>
<section>
<h2>Specific Shorthands</h2>
<ul>
<li class="fragment">
jQuery also sports other shorthands for commonly used actions
<ul>
<li class="fragment"><a href="http://api.jquery.com/load/">$.fn.load()</a> — Load a piece of HTML into an element</li>
<li class="fragment"><a href="http://api.jquery.com/jQuery.getScript/">$.getScript()</a> — Load a piece of JS and run it</li>
<li class="fragment"><a href="http://api.jquery.com/jQuery.getJSON/">$.getJSON()</a> — Load in a piece of JSON</li>
</ul>
</li>
<li class="fragment">These functions only work using <code>GET</code></li>
</ul>
</section>
<section>
<h2>Specific Shorthands: $.fn.load()</h2>
<ul>
<li class="fragment">
Example
<pre class="bigger"><code class="language-javascript dontrun" data-overlay-example="assets/06/examples/jquery.fn.load.html">jQuery(document).ready(function($) {
$('#output').load('html.php');
});</code></pre>
</li>
<li class="fragment">
Also possible to send extra data and hook a success function <em>(see jQuery API)</em>
</li>
</ul>
</section>
<section>
<h2>Specific Shorthands: $.getScript()</h2>
<ul>
<li class="fragment">
Example
<pre class="bigger"><code class="language-javascript dontrun" data-overlay-example="assets/06/examples/jquery.getscript.html">jQuery(document).ready(function($) {
$.getScript('js.php');
});</code></pre>
</li>
<li class="fragment">
Also possible to send extra data and hook a success function <em>(see jQuery API)</em>
</li>
</ul>
</section>
<section>
<h2>Specific Shorthands: $.getJSON()</h2>
<ul>
<li class="fragment">
Example
<pre class="bigger"><code class="language-javascript dontrun" data-overlay-example="assets/06/examples/jquery.getjson.html">jQuery(document).ready(function($) {
$.getJSON('json.php', function(data, textStatus, jqXHR) {
var lecturers = [];
for (var i = 0, len = data.lecturers.length; i < len; i++) {
lecturers.push(data.lecturers[i].name);
}
$('#output').html('<p>' + data.course + ' is taught by ' + lecturers.join(' & ') + '</p>');
});
});</code></pre>
</li>
<li class="fragment">
Also possible to send extra data <em>(see jQuery API)</em>
</li>
</ul>
</section>
<section>
<h2>Sidenote: Multiple Calls</h2>
<ul>
<li class="fragment">
In some cases, you'll need to do 2 requests before you have all needed data
<ul>
<li class="fragment">
Oldskool solution: chain calls
<ul>
<li class="fragment">Invoke call #1</li>
<li class="fragment"><code>success</code> function of call #1 will invoke call #2</li>
<li class="fragment"><code>success</code> function of call #2 will populate the page</li>
</ul>
</li>
<li class="fragment">
Better solution: use the <del>force</del> <ins>deferreds</ins>
<pre class="bigger"><code class="language-javascript dontrun">function doAjax() { return $.get('foo.htm'); }
function doMoreAjax() { return $.get('bar.htm'); }
$.when(doAjax(), doMoreAjax())
.then(function(){
console.log('I am fired once BOTH ajax requests have completed!');
}).fail(function(){
console.log('I am fired if one or more requests failed');
});</code></pre>
</li>
</ul>
</li>
</ul>
</section>
<section>
<h2>What to use?</h2>
<ul>
<li class="fragment">
Shorthands allowed, yet if you want to have full control use <code>$.ajax()</code>
</li>
<li class="fragment">
Use deferreds when requiring multiple resources
</li>
</ul>
</section>
</section>
<!-- 4 : Ajax Challenges -->
<section>
<section>
<h2>Ajax Challenges</h2>
<p><img src="assets/06/futurama_limbo.jpg" alt="" title="" height="315" width="446" /></p>
<q>What's this? Hermes Conrad is closing the gap. He's limbo-ed out of retirement and straight into my heart!</q>
</section>
<section>
<h2>Ajax Challenges</h2>
<ul>
<li class="fragment">
When using Ajax, some usability challenges are faced
<ul>
<li class="fragment">How does the visitor know the site isn't broken but data is loading?</li>
<li class="fragment">The back and previous button (and thus bookmarking of specific content) is broken.
</ul>
</li>
<li class="fragment">
As a developer, you're also facing some technical challenges
<ul>
<li class="fragment">Cross-Domain Communication</li>
<li class="fragment">Working with authentication</li>
</ul>
</li>
</ul>
</section>
<section>
<h2>Ajax Challenges<br /><br />I. User feedback</h2>
</section>
<section>
<h2>User Feedback</h2>
<ul>
<li class="fragment">
Always give the user feedback that something is loading.
<ul>
<li class="fragment">
Textual feedback — viz. “loading”
</li>
<li class="fragment">
Spinners (gifs)
<div style="text-align: center;">
<img src="assets/06/spinners/1-0.gif" />
<img src="assets/06/spinners/2-0.gif" />
<img src="assets/06/spinners/6-0.gif" />
<img src="assets/06/spinners/28-0.gif" /><br />
<img src="assets/06/spinners/19-0.gif" />
</div>
</li>
</ul>
</li>
<li class="fragment">
Generate spinners at <a href="http://ajaxload.info/">ajaxload.info</a>
<ul>
<li class="fragmetn">Also possible with CSS3 nowadays <em>#lmgtfy</em>
</ul>
</li>
</ul>
</section>
<section>
<h2>User Feedback: Example</h2>
<ul>
<li class="fragment">
Show spinner when request is being made, hide spinner when it's done.
<pre class="bigger"><code class="language-html dontrun" data-overlay-example="assets/06/examples/challenges.feedback.html"><img src="spinner.gif" style="display: none;" id="spinner">
<div id="output"></div>
<script src="js/jquery-1.7.1.min.js"></script>
<script>
jQuery(document).ready(function($) {
$('#spinner').show();
$('#output').load('html-delay.php', function() {
$('#spinner').hide();
});
});
</script></code></pre>
</li>
<li class="fragment">
Additionally, when loading data after pressing a button
<ol>
<li class="fragment">Disable the button to prevent the user from clicking it twice</li>
<li class="fragment">Show spinner</li>
</ol>
</li>
</ul>
</section>
<section>
<h2>Ajax Challenges<br /><br />II. Unbreaking History</h2>
</section>
<section>
<h2>History: Hashes</h2>
<ul>
<li class="fragment">
When building a single page interface <em>(think GMail, or even this presentation)</em>, you must enable a way to directly link to a certain part/state of the page.
</li>
<li class="fragment">
Oldskool solution: <em>hashbang URLs</em>
<ul>
<li class="fragment">Change the <code>hash</code> of the <code>window.location</code></li>
<li class="fragment">Listen for the <code>hashchange</code> event to detect wheter a user has clicked the back/forward button and re-apply the state</li>
<li class="fragment">When loading the page, check for a <code>hash</code> and re-apply the state</li>
</ul>
</li>
<li class="fragment">
But really, <a href="http://danwebb.net/2011/5/28/it-is-about-the-hashbangs">don't use hashbang URLs</a>
</li>
</ul>
</section>
<section>
<h2>History: pushState</h2>
<ul>
<li class="fragment">
HTML5 introduced <code>history.pushState()</code> and <code>history.replaceState()</code> which allow you to manipulate the browser <code>history</code> object
<ul>
<li class="fragment">
<code>history.pushState()</code> = add new entry onto history object
</li>
<li class="fragment">
<code>history.replaceState()</code> = replace the current entry in history object
</li>
</ul>
</li>
<li class="fragment">
Whenever user presses back/forward, browser will trigger a <code>popstate</code> event
</li>
</ul>
<footer class="fragment">
Note: the <em>fabricated</em> URLs must also be available when doing a normal request
</footer>
</section>
<section>
<h2>History: pushState Syntax</h2>
<ul>
<li class="fragment">
<code>history.pushState()</code>
<pre class="bigger"><code class="language-javascript dontrun">var stateObj = { foo: "bar" };
history.pushState(stateObj, "page 2", "bar.html");</code></pre>
<ul>
<li class="fragment"><code>stateObj</code> — An object you want to associate with the history entry. Will be returned when <code>popstate</code> is triggered</li>
<li class="fragment"><code>title</code> — Title you wish to link to the history entry <em>(ingored!)</em></li>
<li class="fragment"><code>url</code> — URL to show in the address bar <em>(optional)</em></li>
</ul>
</li>
<li class="fragment">
<code>popstate</code> event
<pre class="bigger"><code class="language-javascript dontrun">window.addEventListener('popstate', function(stateObj) {
console.log(stateObj); // { foo: "bar" }
});</code></pre>