JavaScript is one of the most popular skills in today’s job market. It allows you to create both client- and server-side applications quickly and easily. Having a solid understanding of this powerful and versatile language is essential to anyone who uses it.
“Practical JavaScript Programming” does not only focus on best practices, but also introduces the fundamental concepts. This course will take you from JavaScript basics to advanced. You’ll learn about topics like Data Types, Functions, Events, AJAX and more.
3. 3
Wilson Su
Front-end Developer, HIE
● 6 years in web design
● Specialize in JavaScript /
CSS / HTML / OOP / Git
● Familiar with PHP / Design
Pattern
● Interested in UI & Ix Design
wilson_su@trend.com.tw
4. Outline
4
Practical JavaScript Programming
Chapter 9.
● Form Elements
● Form Events
● Access Form Data
● Validations
● Custom Components
Forms
Chapter 10.
AJAX
● What’s AJAX?
● Handle Request
● Security
● Practices
● Promise
● Server-sent Events
● WebSocket
9. HTML <form> Element With GET Method
9
1. <form action="/search" method="get">
2. <input name="query" type="text" value="keywords"/>
3. <button type="submit">Search</button>
4. </form>
5. <!-- When the form is submitted, the URL will be generated as
'/search?query=keywords' -->
10. HTML <form> Element With POST Method
10
1. <form action="/login" method="post">
2. <label for="user">Username:</label>
3. <input id="user" name="user" type="text" value="guest"/>
4. <label for="pass">Password:</label>
5. <input id="pass" name="pass" type="password" value="12345"/>
6. <button type="submit">Sign In</button>
7. </form>
8. <!-- When the form is submitted, the request body be generated
as 'user=guest&pass=12345' -->
11. Compare GET VS. POST
11
Form Elements
GET POST
Requests data from a specified
resource
Submits data to be processed
to a specified resource
Can be bookmarked Cannot be bookmarkedBookmarked
Can be cached Not cachedCached
Data is visible to everyone in the URL Data is not displayed in the URLVisibility
Harmless Data will be re-submittedBACK button / Reload
The length of a URL is limited No restrictionsMax URL length
14. HTML <input> Events
14
1. var query = document.querySelector('input#query');
2. var logger = function (e) { console.log(e.type); }
3. query.addEventListener('focus', logger);
4. query.addEventListener('input', logger);
5. query.addEventListener('blur', logger);
6. query.addEventListener('change', logger);
7. query.addEventListener('keydown', logger);
8. query.addEventListener('keypress', logger);
9. query.addEventListener('keyup', logger);
10. /* When the input has focus, and user typed one letter */
11. // 'focus', 'keydown', 'keypress', 'input', 'keyup'
12. /* When the input has lost focus */
13. // 'change', 'blur'
15. Focus Events
15
1. <input id="name" type="text"/>
2. <script>
3. var name = document.querySelector('#name');
4. name.addEventListener('focus', (e) => console.log(e.type));
5. name.addEventListener('blur', (e) => console.log(e.type));
6. name.addEventListener('focusin', (e) => console.log(e.type));
7. name.addEventListener('focusout', (e) => console.log(e.type));
8. /* When the input has focus */
9. // 'focus', 'focusin'
10. /* When the input has lost focus */
11. // 'blur', 'focusout'
12. </script>
22. Assigning Default Values
22
1. <form action="/order" method="post">
2. Amount: <input id="amount" type="text"/>
3. <input id="dm" type="checkbox"/> Send me DM
4. <button type="submit">Save</button>
5. <button type="reset">Reset</button>
6. </form>
7. <script>
8. document.querySelector('#amount').value = 0;
9. document.querySelector('#dm').checked = true;
10. /* The input.value will be reset to empty after the Reset
button has been clicked. Use input.defaultValue to assign a
default value. Use input.defaultChecked for checkbox and radio
*/
11. </script>
23. Getting and Setting Values of Input Text and Textarea
23
1. <input id="name" type="text" value="Ben"/>
2. <textarea id="intro" cols="10" rows="5">Ben is a RD</textarea>
3. <script>
4. var name = document.querySelector('#name');
5. var intro = document.querySelector('#intro');
6. console.log(name.value); // 'Ben'
7. console.log(intro.value); // 'Ben is a RD'
8. name.value = 'Vicky';
9. intro.value = 'Vicky is a VD';
10. </script>
24. Getting Values of Checked Checkboxes
24
1. <input name="order" id="1" type="checkbox" value="50" checked>
2. <label for="1">French fries</label>
3. <input name="order" id="2" type="checkbox" value="30" checked>
4. <label for="2">Sprite</label>
5. <script>
6. var selector = '[name="order"]:checked';
7. var selected = document.querySelectorAll(selector);
8. var values = [...selected].map(elem => elem.value);
9. var total = values.reduce((a, b) => +a + +b);
10. console.log(total); // 80
11. </script>
39. Combo Box
39
Custom Components
A combo box allows the user to type in a
single-line input to limit the search, and select
an item from a list of matched options.
Combo box interaction specs ( incomplete ) :
● Click the caret button to open options
● Type keywords to filter options
● Arrow buttons to highlight an option
● Press enter to set value with the
highlighted option
● Click cancel button to clear search
40. 40
Date Picker
The date picker contains the date input field
and the calendar view. Users can either use
the input field to type a date or by selecting a
date in the calendar.
Date picker interaction specs ( incomplete ) :
● Focus input to open a canlendar
● Press keyboard arrows to switch year,
month, and date
● Click arrows to switch months
● Click a date to set value
Custom Components
43. AJAX
43
● AJAX is an acronym for Asynchronous
JavaScript and XML
● It is a web technique that allows for more
interactivity by making web pages that
fetch data in the background and alter
themselves without reloading the entire
page.
● A user can continue to use the
application while the client program
requests information from the server in
the background.
What’s AJAX?
44. A Traditional Web Application
44
What’s AJAX?
Client Server
User Interface Web Server
Data Beckend
HTTP Request
HTML + CSS + JS
45. An AJAX Web Application
45
What’s AJAX?
User Interface Web Server
Data BeckendAJAX Engine
Client Server
HTTP Request
JS Call Data
Data
(XML / TEXT / HTML / JSON)
47. Making an AJAX Request
47
1. var xhr = new XMLHttpRequest();
2. xhr.onreadystatechange = function () {
3. if (xhr.readyState === xhr.DONE && xhr.status === 200) {
4. console.log(xhr.responseText);
5. // <button id="{{id}}" type="button">{{action}}</button>
6. }
7. };
8. xhr.open('get', '/templates/button.html', true);
9. xhr.send();
48. Making a Synchronous Request
48
1. var xhr = new XMLHttpRequest();
2. xhr.open('GET', '/data/cars.json', false);
3. xhr.send();
4. console.log(xhr.responseText);
5. // '["audi","benz","bmw"]'
49. Synchronous XMLHttpRequest
makes the JavaScript stop
executing until the server
response is ready. If the server
is busy or slow, the application
will hang or stop.
49
52. Working with XML Data
52
1. /* Given a XML file 'food.xml' as follows:
2. <?xml version="1.0" encoding="UTF-8"?>
3. <root><food>Pizza</food><food>Bread</food></root>
4. */
5. request('get', '/data/food.xml', function (xhr) {
6. var nodes = xhr.responseXML.getElementsByTagName('food');
7. var data = [...nodes].map(node => node.textContent);
8. console.log(data); // (2) ['Pizza', 'Bread']
9. })
10. .send();
53. Using POST Method in XMLHTTPRequest
53
1. var item = 'item=iphone';
2. var amount = 'amount=99';
3. var params = [item, amount].join('&');
4. var contentType = 'application/x-www-form-urlencoded';
5. var xhr = request('post', '/order', function (xhr) {
6. console.log(xhr.responseText);
7. // '{"data":{"item":"iphone","amount":"99"}}'
8. });
9. xhr.setRequestHeader('Content-type', contentType);
10. xhr.send(params);
54. Encoding a URI Component
54
1. var hello = '你好';
2. var param = 'text=' + encodeURIComponent(hello);
3. var url = '/echo?' + param;
4. request('get', url, function (xhr) {
5. console.log(xhr.responseText); // '你好'
6. })
7. .send();
55. Uploading a File
55
1. <input id="file" type="file"/>
2. <script>
3. var file = document.querySelector('#file').files[0];
4. var data = new FormData();
5. var xhr = request('post', '/upload');
6. data.append('target', 'images');
7. data.append('file', file, 'sky.jpg');
8. xhr.send(data);
9. </script>
56. Monitoring Progress of a File Upload
56
1. var file = document.querySelector('#file').files[0];
2. var data = new FormData();
3. var xhr = request('post', '/upload');
4. data.append('file', file);
5. xhr.upload.addEventListener('progress', function (e) {
6. if (e.lengthComputable) {
7. console.log(Math.floor(e.loaded / e.total * 100));
8. }
9. });
10. xhr.send(data);
59. URL Outcome Reason
http://www.abc.com/about/contact.html Success Same protocol, host and port
http://www.abc.com/service/training.html Success Same protocol, host and port
https://www.abc.com/member/login.html Failure Different protocol
http://www.abc.com:8080/partners.html Failure Different port
http://abc.com/blog/tags.html Failure Different host
Same-origin Policy
59
The same-origin policy restricts how a document or script loaded from one
origin can interact with a resource from another origin.
The following table gives examples of origin comparisons to the URL
http://www.abc.com/about/index.html:
Security
60. Cross-Origin Resource Sharing
CORS is a system, consisting of transmitting HTTP headers, that
determines whether to block or fulfill requests for restricted resources on a
web page from another domain outside the domain from which the
resource originated.
To allow any resource to access your resource, you can specify:
Access-Control-Allow-Origin: *
To allow https://www.abc.com to access your resource, you can specify:
Access-Control-Allow-Origin: https://www.abc.com
60
Security
61. JSON with Padding
61
JSONP is used to request data from a server residing in a different domain
than the client.
JSONP
Client
Server
<script>function fn (data) { … }</script>
<script src="https://api.su.com/users/9?callback=fn"></script>
response.setHeader('Content-type', 'text/javascript');
response.send('fn({ "id": 9, "name": "Kyle" })');
72. What’s a Promise?
72
A Promise is an object representing the eventual completion or failure of
an asynchronous operation. – MDN
Promise
Promise
.then(onFulfilled)
.catch(onRejected)
Promise …
pending
resolved
rejected
pending
return
81. Server-sent Events
81
SSE is a technology where a browser receives automatic updates from a
server via HTTP connection. – Wiki
Request
Response
Request
Response
Handshake
Acknowledgement
Server push
Server push
CLIENT SERVER
Polling
CLIENT SERVER
Server-sent Event
VS.
82. Receiving Server-Sent Event Notifications
82
1. var es = new EventSource('http://localhost/stream');
2.
3. es.addEventListener('open', function (e) { … });
4. es.addEventListener('error', function (e) { … });
5. es.addEventListener('message', function (e) {
6. console.log(JSON.parse(e.data));
7. });
8. es.addEventListener('custom-event', function (e) {
9. console.log(JSON.parse(e.data));
10. });
84. WebSocket is a computer communications protocol, providing full-duplex
communication channels over a single TCP connection. – Wiki
What Is WebSocket?
84
WebSocket
Request
Response
Request
Response
Handshake
Acknowledgement
Bi-directional
messages
Connection end
CLIENT SERVER
HTTP
CLIENT SERVER
WebSocket
VS.
Connection lifecycle Connection lifecycle
85. Creating a WebSocket Object
85
1. var ws = new WebSocket('wss://localhost');
2.
3. ws.addEventListener('open', function (e) { … });
4. ws.addEventListener('error', function (e) { … });
5. ws.addEventListener('message', function (e) {
6. console.log(JSON.parse(e.data));
7. // { success: true, action: 'echo', data: 'Bye' }
8. ws.close();
9. };
10. ws.send(JSON.stringify({ action: 'echo', data: 'Bye' }));
86. Reference
86
● Ajax (programming) - Wikipedia
● CORS - Glossary | MDN
● Cross-origin resource sharing - Wikipedia
● GET vs POST - Difference and Comparison | Diffen
● JavaScript | MDN
● JSONP - Wikipedia
Practical JavaScript Programming
87. Reference
● Same-origin policy - Wikipedia
● Same-origin policy - Web security | MDN
● Server-sent events - Wikipedia
● WebSocket - Wikipedia
87
Practical JavaScript Programming