Slide 1

Slide 1 text

JavaScript in Browser Environment Jussi Pohjolainen

Slide 2

Slide 2 text

Single-page Applications (SPA) • Web app that fits on a single web page • Fluid UX, like desktop app • Examples like Gmail, Google maps • Html page contains mini-views (HTML Fragments) that can be loaded in the background • No reloading of the page, better UX • Requires handling of browser history, navigation and bookmarks

Slide 3

Slide 3 text

JavaScript • SPAs are implemented using JavaScript and HTML • Usually we use some framework for this • ECMAScript is a scripting language, standardized by Ecma International • In Browsers, ECMAScript is commonly called JavaScript • JavaScript = Native (EcmaScript) + Host objects (browser)

Slide 4

Slide 4 text

JavaScript • EcmaScript • String, Number, Operators, Statements, Math, Date, Array, Boolean, RegExp.. • Browser BOM • window, navigator, screen, history, location • HTML DOM • DOM document, element, attribute, events • JavaScript = EcmaScript + BOM + DOM

Slide 5

Slide 5 text

Learning Path for Front-end Core EcmaScript Browser Host Objects JavaScript in Front-end HTML5 CSS Static Web-pages JavaScript Frameworks: React, AngularJS, ... Also basic understanding of HTTP and REST API...

Slide 6

Slide 6 text

HTTP

Slide 7

Slide 7 text

HTTP network protocol • HTTP is a network protocol of the Web • Hypertext Transfer Protocol • Delivers resources on the WWW • Usually delivered by TCP/IP • HTTP client sends a request to HTTP server • Default port is 80 • Resource can be a file or dynamically generated query result

Slide 8

Slide 8 text

Structure of HTTP • Consists of request and response • Format • an initial line, • zero or more header lines, • a blank line, • optional message body (this is the resource) • Example Header1: value1 Header2: value2

Slide 9

Slide 9 text

HTTP REQUEST: Initial Line • Initial line is different for the request than response. • Request line has three parts • method name, local path to resource, version of http • Example • GET /path/to/file/index.html HTTP/1.0 • Method name can be GET, POST, PUT, DELETE...

Slide 10

Slide 10 text

HTTP RESPONSE: Initial Line • The initial response line, called the status line • Typical status lines • HTTP/1.0 200 OK • HTTP/1.0 404 Not Found • Status code (200, 404) is computer-readable, reason phrase is human-readable • Status codes • 1xx, information message • 2xx, success • 3xx, redirect • 4xx, client error • 5xx, server error • See all status codes • http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

Slide 11

Slide 11 text

Header Lines • Header lines provide information about the request and response • Header-name: value • HTTP 1.0 provides 16 headers, HTTP 1.1 provides 46 headers • For example client should tell who is making the request • User-Agent: ... • Server should identify • Server: ...

Slide 12

Slide 12 text

Message Body • Message body contains the resource • Usually the message body includes header lines • Content-type: • MIME type of the resource, for example text/html, image/gif • Content-length • bytes

Slide 13

Slide 13 text

Example HTTP REQUEST and HTTP RESPONSE GET /tekstiedosto.txt HTTP/1.1 Host: localhost:8080 User-Agent: curl/7.49.1 Accept: text/json HTTP/1.1 200 OK Server: GlassFish Server Open Source Edition 4.1.1 X-Powered-By: Servlet/3.1 JSP/2.3 (GlassFish Server Open Source Edition 4.1.1 Java/Oracle Corporation/1.8) Content-Type: text/xml;charset=ISO-8859-1 Date: Tue, 10 Jan 2017 10:27:34 GMT Content-Length: 12 Hello World

Slide 14

Slide 14 text

Example HTTP REQUEST and HTTP RESPONSE POST /MunSoftaniTestaus/MunHienoServlet HTTP/1.1 Host: localhost:8080 User-Agent: curl/7.49.1 Accept: */* Content-type: text/plain Content-Length: 9 Some data HTTP/1.1 200 OK Server: GlassFish Server Open Source Edition 4.1.1 X-Powered-By: Servlet/3.1 JSP/2.3 (GlassFish Server Open Source Edition 4.1.1 Java/Oracle Corporation/1.8) Content-Type: text/plain;charset=ISO-8859-1 Date: Tue, 10 Jan 2017 10:39:58 GMT Content-Length: 9 Some data

Slide 15

Slide 15 text

Lab

Slide 16

Slide 16 text

HTML5 and JS

Slide 17

Slide 17 text

HTML5: It's really easy! Title The content

Slide 18

Slide 18 text

HTML5 vs XHTML5: MIME • HTML5 • text/html • XHTML5 • application/xhtml+xml • See: • https://wiki.whatwg.org/wiki/HTML_vs._XHTML

Slide 19

Slide 19 text

Simple Embedded JS Title console.log('hello world') JS part of the Web page

Slide 20

Slide 20 text

Simple External JS Title Let's fetch the JS from external file

Slide 21

Slide 21 text

Lab

Slide 22

Slide 22 text

Browser Object Model

Slide 23

Slide 23 text

Browser Object Model • Browser specific convention to all the objects exposed by web browser • There is no standard implementation and no strict definition • Browser vendors are free to implement BOM • In Browsers, you use EcmaScript + Host Objects • Host Objects are • BOM (Browser object model) • DOM (Document object model) • DOM has strict definition from W3C / WHATWG

Slide 24

Slide 24 text

chrome location document history navigator applicationCache screen ... window Some BOM objects in Chrome getElementsByTagName createTextNode appendChild removeChild ...

Slide 25

Slide 25 text

Lab

Slide 26

Slide 26 text

Handling Events

Slide 27

Slide 27 text

Intro to Events • Some interaction on html – page: • Mouse click (onclick) • Web page loading (onload) • Mousing over and out (onmouseover, onmouseout) • Submitting HTML form (onsubmit) • Key handling, web page completing, user scrolling or resizing …

Slide 28

Slide 28 text

Evolution of Events • DOM Level 0 (Introduced in Netscape) • Say hello • DOM Level 2 (W3C) • document.getElementById("my-link").addEventListener("click", myFunction, false); • Microsoft (IE) did not follow the W3C model until IE8. IE11 deletes its support for MS model

Slide 29

Slide 29 text

Example Handler Properties • button.onfocus • button.onblur • button.ondblclick • button.onmouseover • button.onmouseout • window.onkeypress • window.onkeydown • window.onscroll

Slide 30

Slide 30 text

Inline Event Handler Title function doIt() { console.log("Hello"); } Click

Slide 31

Slide 31 text

Inline Event Handler • Try to avoid inline event handlers they are considered bad practice • Avoid mixing html and js! • If you have "100 buttons", the maintanence of these can be hard

Slide 32

Slide 32 text

Better Way Title function clicked() { console.log("click"); } function ready() { var b = document.querySelector("#mybutton"); b.ondblclick = clicked; } window.onload = ready; Click

Slide 33

Slide 33 text

Canceling Default Behaviour: return false Title function clicked(event) { console.log("click"); return false; } function ready() { var b = document.querySelector("#link"); b.onclick = clicked; } window.onload = ready; Click Won't open mozilla.org

Slide 34

Slide 34 text

Title function count() { var height = document.forms.myform.height.value; var weight = document.forms.myform.weight.value; document.forms.myform.result.value = (weight / (height*height)); } window.onload = () => { let button = document.querySelector('#button') button.onclick = count; } Height (m):

Weight (kg):


BMI
Accessing Form by using DOM Level 0

Slide 35

Slide 35 text

Lab

Slide 36

Slide 36 text

W3C DOM • DOM – Document Object Model – cross-platform and language- independent convention for interacting with objects in HTML and in XML. • With DOM you can manipulate html/xml document! Dynamic html! • Public interface available: http://www.w3.org/DOM/DOMTR

Slide 37

Slide 37 text

W3C DOM Levels (Legacy) • ( DOM Level 0 and Intermediate DOM ) • Not W3C Standards, used in Netscape 2 (Level 0) and Netscape 4 (Intermediate DOM) • DOM Level 1 • 1998: Ability to change entire HTML or XML document • Core and HTML specifications • Level of support: excellent • DOM Level 2 • 2001: Introduces “getElementById” function, event model and support for XML namespaces • Core, Views, Events, Style, Traversal and Range, HTML • Level of Support: good • DOM Level 3 • 2004: XPath, focus on keyboard event handling • Core, Load, Save, Validation, Events, XPath

Slide 38

Slide 38 text

WHATWG: DOM Living Standard • WHATWG DOM "standardizes" DOM • DOM LEVEL 3 core and DOM LEVEL 3 Events • Selectors API Level 2 • And others • https://dom.spec.whatwg.org/

Slide 39

Slide 39 text

DOM (Level 2) Event Handling • Methods for adding and removing events • addEventListener • removeEventListener • Multiple event handlers can be registered for the same event!

Slide 40

Slide 40 text

Title window.addEventListener('load', ready); function ready() { let p = document.querySelector("#clickme"); p.addEventListener('click', doIt); } function doIt() { alert("Hello"); }

click

Slide 41

Slide 41 text

Benefits • You can remove event listener • You can register multiple listeners

Slide 42

Slide 42 text

Remove function ready() { let p = document.querySelector("#clickme"); p.addEventListener('click', doIt); } function doIt() { alert("Hello"); let p = document.querySelector("#clickme"); p.removeEventListener('click', doIt); }

Slide 43

Slide 43 text

Multiple Listeners function ready() { let p = document.querySelector("#clickme"); p.addEventListener('click', () => alert("Hello")); p.addEventListener('click', () => alert("World")); }

Slide 44

Slide 44 text

Event Object window.addEventListener('load', ready); function ready() { let p = document.querySelector("#clickme"); p.addEventListener('click', doIt); } function doIt(event) { alert("hello"); let p = event.target; p.removeEventListener('click', doIt); } It's an event -object

Slide 45

Slide 45 text

Event Object function ready() { let p = document.querySelector("#clickme"); p.addEventListener('click', doIt); } function doIt(event) { console.log(event.type); console.log(event.timeStamp); } See doc for all possibilities

Slide 46

Slide 46 text

Lab

Slide 47

Slide 47 text

Event Bubbling div p If div and p both have click – event handler?

Slide 48

Slide 48 text

stopPropagation: only p will trigger function ready() { let p = document.querySelector("#pClickme"); let div = document.querySelector("#divClickMe"); p.addEventListener('click', (e) => { e.stopPropagation(); alert("p");} ); div.addEventListener('click', (e) => alert("div")); }

Slide 49

Slide 49 text

Pattern: Listen to children
  • Hello
  • World

Slide 50

Slide 50 text

Script function ready() { let ul = document.querySelector("#list"); ul.addEventListener('click', (e) => { console.log(e.target); //
  • Hello
  • console.log(e.target.nodeName); // LI if(e.target.nodeName == "LI") { alert(e.target.id); // item-1 or item-2 } } ); }

    Slide 51

    Slide 51 text

    Lab

    Slide 52

    Slide 52 text

    Document Object Model

    Slide 53

    Slide 53 text

    DOM • Programming Interface for HTML and XML documents • You can change dynamically the document using DOM • The document is presented in nodes • Most browsers support both • W3C DOM • WHATWG DOM • And in addition have extensions to these • DOM is not a programming language, it's an specification

    Slide 54

    Slide 54 text

    WHATWG: DOM Living Standard • DOM For all structured Documents • WHATWG DOM "standardizes" DOM • DOM LEVEL 3 core and DOM LEVEL 3 Events • Selectors API Level 2 • And others • https://dom.spec.whatwg.org/ • For HTML also additions • https://html.spec.whatwg.org/multipage/dom.html • Other languages support also DOM, not just JavaScript

    Slide 55

    Slide 55 text

    document • document object represents the web page loaded • Is the entry point into web page's content (DOM Tree) • Some methods for getting elements • getElementsById(id) • getElementsByTagName(name) • querySelector(cssselector) • The DOM tree can be traversed in a lot of different ways • DOM Tree consists of nodes. Node can be for example • element, attribute, text ...

    Slide 56

    Slide 56 text

    Title var htmlElementNode = document.documentElement; console.log(htmlElementNode instanceof Node); // true // Element extends Node console.log(htmlElementNode instanceof Element); // true console.log(htmlElementNode.getAttribute("hello")) // world

    Slide 57

    Slide 57 text

    Node? • Node is a base "class" for • Element, Document, Text ... • For each Node you can use • childNodes() • firstChild() • lastChild() • nextSibling() • nodeType() • nodeValue • textContent()

    Slide 58

    Slide 58 text

    Node • In DOM, each object is Node • In this •

    Hello

    • You have two nodes 1) element node p 2) text node Hello • Text node is child node of p element. P element is parent node of the text node

    Slide 59

    Slide 59 text

    My Title var htmlElementNode = document.documentElement; var headElementNode = htmlElementNode.firstChild; var titleElementNode = headElementNode.firstChild; var titleTextNode = titleElementNode.firstChild; var titleString = titleTextNode.nodeValue; console.log(titleString);

    Slide 60

    Slide 60 text

    My Title var htmlElementNode = document.documentElement; var helloAttributeNode = htmlElementNode.getAttributeNode("hello"); var attributeText = helloAttributeNode.nodeValue console.log(attributeText);

    Slide 61

    Slide 61 text

    Getting Elements More Easier • Getting list of elements • document.getElementsByTagName() • Getting with id • document.getElementById() • Getting use CSS selectors • document.querySelector()

    Slide 62

    Slide 62 text

    My Title

    Title 1

    Title 2

    var allH1Elements = document.getElementsByTagName("h1"); var firstH1 = allH1Elements[0]; firstH1.firstChild.nodeValue = "Hello!"; Getting all elements with tag H1

    Slide 63

    Slide 63 text

    My Title

    Title 1

    Title 2

    var firstH1 = document.getElementById("mytitle"); firstH1.firstChild.nodeValue = "Hello!"; Getting H1 with the id of mytitle

    Slide 64

    Slide 64 text

    My Title

    Title 1

    Title 2

    var firstH1 = document.querySelector("#mytitle"); firstH1.firstChild.nodeValue = "Hello!"; Using CSS Query Selector for getting the H1

    Slide 65

    Slide 65 text

    Lab

    Slide 66

    Slide 66 text

    Whitespaces.... We have a problem! My Title

    Title

    var div = document.querySelector("#myDiv"); var h1 = div.firstChild; var text = h1.firstChild; text.nodeValue = "Hello"; We are NOT getting the H1 Here!

    Slide 67

    Slide 67 text

    https://javascript.info/dom-nodes head child is a text node!

    Slide 68

    Slide 68 text

    Title

    var div = document.querySelector("#myDiv"); var whiteSpace = div.firstChild; var h1 = whiteSpace.nextSibling; var text = h1.firstChild; text.nodeValue = "Hello";

    Slide 69

    Slide 69 text

    firstChild vs firstElementChild

    Title

    var div = document.querySelector("#myDiv"); var h1 = div.firstElementChild; var text = h1.firstChild; text.nodeValue = "Hello"; Bypassing the text node..

    Slide 70

    Slide 70 text

    textContent

    Title

    var div = document.querySelector("#myDiv"); var h1 = div.firstElementChild; //var text = h1.firstChild; //text.nodeValue = "Hello"; h1.textContent = "Hello";

    Slide 71

    Slide 71 text

    textContent vs innerHTML
    var div = document.querySelector("#myPre"); div.textContent = "<h1>Moi</h1>"; In browser we are seeing also the < and > characters

    Slide 72

    Slide 72 text

    textContent vs innerHTML
    var div = document.querySelector("#myPre"); div.innerHTML = "<h1>Moi</h1>"; In innerHTML the

    and

    are presented as tags..

    Slide 73

    Slide 73 text

    Lab

    Slide 74

    Slide 74 text

    Creating and appending function main(event) { let h1 = document.createElement("h1") let text = document.createTextNode("Hello World") h1.appendChild(text) document.getElementsByTagName("body")[0].appendChild(h1) } window.addEventListener('load', main) Creating new elements and text nodes!

    Slide 75

    Slide 75 text

    Creating attribute function main(event) { let a = document.createElement("a") a.setAttribute("href", "http://www.tamk.fi") let text = document.createTextNode("tamk") a.appendChild(text) document.getElementsByTagName("body")[0].appendChild(a) } window.addEventListener('load', main)

    Slide 76

    Slide 76 text

    insertBefore My Title function main(event) { let a = document.createElement("a") a.setAttribute("href", "http://www.tamk.fi") let text = document.createTextNode("tamk") a.appendChild(text) let p = document.getElementById("someid") let parent = p.parentElement parent.insertBefore(a, p) } window.addEventListener('load', main)

    Hello

    Insert the link (a) before the p under body

    Slide 77

    Slide 77 text

    removeChild My Title function main(event) { let body = document.getElementsByTagName('body')[0] let p = document.getElementById('someid') body.removeChild(p) } window.addEventListener('load', main)

    Hello

    Slide 78

    Slide 78 text

    replaceChild My Title function main(event) { let body = document.getElementsByTagName('body')[0] let p = document.getElementById('someid') let h1 = document.createElement('h1') h1.appendChild(document.createTextNode('Hello World')) body.replaceChild(h1, p) } window.addEventListener('load', main)

    Hello

    Slide 79

    Slide 79 text

    Lab

    Slide 80

    Slide 80 text

    AJAX XmlHttpRequest, Promises and Fetch

    Slide 81

    Slide 81 text

    AJAX • AJAX: Asynchronous JavaScript and XML • AJAX is about updating parts of web page without reloading the whole page • Essential part when creating Single Page Apps!

    Slide 82

    Slide 82 text

    How AJAX works? (javatpoint.com)

    Slide 83

    Slide 83 text

    Synchronous vs Asynchronous • Synchronous requests blocks the client (browser unresponsive) until request is done • Asynchronous requests does not block the client -> User can interact with the web page while at the same time the request is being fulfilled • Asynchronous requests usually work with callbacks or Promises • AJAX requests are asynchronous, also web workers and setTimeout

    Slide 84

    Slide 84 text

    XMLHttpRequest • Modern browsers support built-in XMLHttpRequest object • All about sending and receiving data from server. • Instantiate in normal fashion: • var xmlobj = new XMLHttpRequest();

    Slide 85

    Slide 85 text

    My Title function buttonClicked(event) { var xmlobj = new XMLHttpRequest(); xmlobj.open("GET", // HTTP POST or GET? "./somefile.txt", // URL true); // async or not? xmlobj.send(); // Send it } window.addEventListener('load', (event) => { document.getElementById('myButton').addEventListener('click', buttonClicked) }) Fetch

    Slide 86

    Slide 86 text

    AJAX is not supported with file://

    Slide 87

    Slide 87 text

    To quickly create Web Server (http) • Install Node.js • Install http-server module globally: • npm install http-server –g • Then start the http-server in your project folder: • http-server • Open browser • http://127.0.0.1:8080

    Slide 88

    Slide 88 text

    No errors when using HTTP

    Slide 89

    Slide 89 text

    Asynchronous • When setting the async parameter to true, the server side script is run in background. • Javascript does not have to wait for the server response.. You can • Execute other scripts while waiting server response • Deal with the response when ready • Specify a function that is called when response is ready!

    Slide 90

    Slide 90 text

    onreadystatechange function buttonClicked(event) { var xmlobj = new XMLHttpRequest(); xmlobj.onreadystatechange = function() { console.log(xmlobj.readyState) } xmlobj.open("GET", "./somefile.txt", true); xmlobj.send(); }

    Slide 91

    Slide 91 text

    readystate?

    Slide 92

    Slide 92 text

    State of the Request • 0: Not initialized • 1: open() has been called • 2: send() has been called • 3: loading • 4: request finished and response Ready

    Slide 93

    Slide 93 text

    responseText function buttonClicked(event) { var xmlobj = new XMLHttpRequest(); xmlobj.open("GET", "./somefile.txt", true); xmlobj.onreadystatechange = function() { if(xmlobj.readyState == 4) { console.log(xmlobj.responseText) } } xmlobj.send(); }

    Slide 94

    Slide 94 text

    Usage

    Slide 95

    Slide 95 text

    Status of the Request • Also HTTP Status is received • 200: “Ok” • 404: “Page not found” • … • if(xmlobj.status == 200 && xmlobj.readyState == 4) { .. }

    Slide 96

    Slide 96 text

    With status function buttonClicked(event) { var xmlobj = new XMLHttpRequest(); xmlobj.open("GET", "./somefile.txt", true); xmlobj.onreadystatechange = function() { if(xmlobj.readyState == 4 && xmlobj.status == 200) { console.log(xmlobj.responseText) } } xmlobj.send(); }

    Slide 97

    Slide 97 text

    AJAX and DOM function buttonClicked(event) { var xmlobj = new XMLHttpRequest(); xmlobj.open("GET", "./somefile.txt", true); xmlobj.onreadystatechange = function() { if(xmlobj.readyState == 4 && xmlobj.status == 200) { document.getElementById('content').innerHTML = xmlobj.responseText } } xmlobj.send(); }

    Slide 98

    Slide 98 text

    Lab

    Slide 99

    Slide 99 text

    Server Response • XMLHttpRequest has two attributes for the response • DOMString responseText • Document responseXML

    Slide 100

    Slide 100 text

    students.xml Tina Smith Paul Power

    Slide 101

    Slide 101 text

    function buttonClicked(event) { var xmlobj = new XMLHttpRequest(); xmlobj.open("GET", "./students.xml", true); xmlobj.onreadystatechange = function() { if(xmlobj.readyState == 4 && xmlobj.status == 200) { let doc = xmlobj.responseXML let students = doc.getElementsByTagName("student") let firststudent = students[0] let firststudentname = firststudent.textContent document.getElementById('content').innerHTML = firststudentname } } xmlobj.send(); }

    Slide 102

    Slide 102 text

    students.json [{"name": "Tina Smith"}, {"name": "Paul Power"}]

    Slide 103

    Slide 103 text

    Parsing JSON function buttonClicked(event) { var xmlobj = new XMLHttpRequest(); xmlobj.open("GET", "./students.json", true); xmlobj.onreadystatechange = function() { if(xmlobj.readyState == 4 && xmlobj.status == 200) { let text = xmlobj.responseText let jsonArray = JSON.parse(text) document.getElementById('content').innerHTML = jsonArray[0].name } } xmlobj.send(); }

    Slide 104

    Slide 104 text

    Lab

    Slide 105

    Slide 105 text

    HTTP Access Control

    Slide 106

    Slide 106 text

    function buttonClicked(event) { var xmlobj = new XMLHttpRequest(); xmlobj.open("GET", "http://www.thomas-bayer.com/sqlrest/CUSTOMER/0/", true); xmlobj.onreadystatechange = function() { if(xmlobj.readyState == 4 && xmlobj.status == 200) { let doc = xmlobj.responseXML let firstname = doc.getElementsByTagName("FIRSTNAME")[0].textContent document.getElementById('content').innerHTML = firstname } } xmlobj.send(); }

    Slide 107

    Slide 107 text

    No content

    Slide 108

    Slide 108 text

    Same-origin policy • For security reasons, by default, XMLHttpRequest following same- origin policy • Only http requests to its own domain! • So access from 127.0.0.1/index.html -> 127.0.0.1/students.xml is allowed • From 127.0.01/index.html -> someothersite.com/students.xml is NOT allowed!

    Slide 109

    Slide 109 text

    Students.xml on koti.tamk.fi

    Slide 110

    Slide 110 text

    AJAX 127.0.0.1 -> koti.tamk.fi

    Slide 111

    Slide 111 text

    CORS • Cross – Origin Resource Sharing (CORS) mechanism gives cross- domain access controls • enables secure cross-domain data transfers • Works by adding new HTTP Headers

    Slide 112

    Slide 112 text

    Access-Control-Allow-Origin

    Slide 113

    Slide 113 text

    There is no Access- Control-Allow-Origin! Cross-domain requests from AJAX are not allowed

    Slide 114

    Slide 114 text

    Adding a new header: students.php Tina Smith Paul Power

    Slide 115

    Slide 115 text

    Server allows cross origin ajax calls

    Slide 116

    Slide 116 text

    Try it again... it should work! function buttonClicked(event) { var xmlobj = new XMLHttpRequest(); xmlobj.open("GET", "http://koti.tamk.fi/~pohjus/cors/students.php", true); xmlobj.onreadystatechange = function() { if(xmlobj.readyState == 4 && xmlobj.status == 200) { let doc = xmlobj.responseXML let firstname = doc.getElementsByTagName("student")[0].textContent document.getElementById('content').innerHTML = firstname } } xmlobj.send(); }

    Slide 117

    Slide 117 text

    Third party API

    Slide 118

    Slide 118 text

    Using curl

    Slide 119

    Slide 119 text

    Lab

    Slide 120

    Slide 120 text

    Using POST var xmlobj = new XMLHttpRequest(); xmlobj.open("POST", // POST or GET? "somescript.php", // URL true); // async or not? // Specify the data you want to send via POST xmlobj.setRequestHeader("Content-type","application/x-www-form-urlencoded"); // Send data xmlobj.send("name=Kalle");

    Slide 121

    Slide 121 text

    Promises

    Slide 122

    Slide 122 text

    About Promises • Fetch API is a new way of doing AJAX • Fetch API uses Promises • Promises an alternative to callbacks delivering result of an async computation • Promises are part of EcmaScript 2015 • Previously you could use them as additional library • https://promisesaplus.com/ 122

    Slide 123

    Slide 123 text

    Typical async function with callback asyncFunction(arg1, arg2, result => { console.log(result); }); 123

    Slide 124

    Slide 124 text

    Problems with callbacks • When async done, do another async method (chaining) -> using callbacks can be messy • What is async fails? If you have chained async methods and one of them fails? • It is not standard, everyone can have they own version of doing callbacks 124

    Slide 125

    Slide 125 text

    Using Promises function promiseFunction(resolve, reject) { // time consuming async stuff if(true) { resolve("OK!"); } else { reject("Failed!"); } } function onSuccess(msg) { console.log(msg); } function onError(msg) { console.log(msg); } let promise = new Promise(promiseFunction); promise.then(onSuccess, onError); promise.then(onSuccess).catch(onError); You can do both here 125

    Slide 126

    Slide 126 text

    Node.JS callbacks const fs = require('fs'); fs.readFile('mytest.json', function (error, text) { if (error) { console.error('Error while reading config file'); } else { try { const obj = JSON.parse(text); console.log(JSON.stringify(obj)); } catch (e) { console.error('Invalid JSON in file'); } } } ); File I/O module 126

    Slide 127

    Slide 127 text

    Node.JS promise const util = require('util'); const fs = require('fs'); const promiseReadFile = util.promisify(fs.readFile); promiseReadFile('mytest.json') .then(function (text) { // const obj = JSON.parse(text); console.log(JSON.stringify(obj)); }) .catch(function (error) { // // File read error or JSON SyntaxError console.error('An error occurred', error); }); util.promisify is Node 8 feature 127

    Slide 128

    Slide 128 text

    Simple Example function doSomeTimeConsumingStuff() { function asyncOperation(resolve, reject) { setTimeout(() => resolve("Done"), 1000); } return new Promise(asyncOperation); } doSomeTimeConsumingStuff().then(result => console.log('Result: ' + result)); 128

    Slide 129

    Slide 129 text

    function promiseFunction(resolve, reject) { // time consuming async stuff if(true) { resolve(4); } else { reject("First promise failed!"); } } function onSuccess(result) { let p = new Promise((resolve, reject) => { // time consuming async stuff if(true) { resolve(result + 4); } else { reject("Second promise failed"); } } ); return p; } function onError(msg) { console.log(msg); } let promise = new Promise(promiseFunction); promise.then(onSuccess).then((result) => console.log("sum = " + result)).catch(onError); Returns promise Chaining with then Can handle both errors! 129

    Slide 130

    Slide 130 text

    Fetch API

    Slide 131

    Slide 131 text

    Fetch API • Alternative (new) way of doing AJAX • Whatwg living standard • https://fetch.spec.whatwg.org/ • Uses promises

    Slide 132

    Slide 132 text

    function doIt(event) { function responseIsReady(response) { return response.json() } function jsonIsParsed(studentsJsonArray) { document.getElementById('content').innerHTML = studentsJsonArray[0].name } // studens.json: [{"name": "Tina Smith"}, {"name": "Paul Power"}] fetch('./students.json').then(responseIsReady).then(jsonIsParsed) } window.addEventListener('load', (event) => { document.getElementById('myButton').addEventListener('click', doIt); })

    Slide 133

    Slide 133 text

    To Extract Body • json() • text() • blob() • formData() • ...

    Slide 134

    Slide 134 text

    Error Handling fetch('http://..../customers').then(function(response) { var contentType = response.headers.get('content-type'); // status 200 - 299 if(!response.ok) { throw new Error('Network response was not ok!'); } if(!contentType.includes('application/json')) { throw new Error('It was not json') } return response.json(); }).then(function(jsonObject) { // do something with the jsonObject }).catch(function(error) { console.log('There has been a problem with your fetch operation: ' + error.message); });

    Slide 135

    Slide 135 text

    POST var myHeaders = new Headers() myHeaders.append('Content-type', 'text/json') var init = { method: 'post', headers: myHeaders, body: {'name': 'jack'} } fetch('http://www.company.com/api/students', init).then(responseIsReady).then(jsonIsParsed)

    Slide 136

    Slide 136 text

    Lab

    Slide 137

    Slide 137 text

    FormData • FormData is a easy way of creating key/value pairs from a form • When having a form in HTML page you can just create the FormData by • let formData = new FormData(someFormDomElement) • Then by using Fetch API or XmlHttpRequest, it's really easy to send user given values to backend

    Slide 138

    Slide 138 text

    Example function doIt (event) { let formData = new FormData(document.getElementById('myForm')) var init = { method: 'post', body: formData } fetch('http://.../postdata.php', init).then(responseIsReady).then(jsonIsParsed) }

    Slide 139

    Slide 139 text

    Webpack

    Slide 140

    Slide 140 text

    Webpack • Bundles several JS – files into one • Supports ES 2015 modules • Install locally • npm install --save-dev webpack

    Slide 141

    Slide 141 text

    Title The content Webpack will generate this for us!

    Slide 142

    Slide 142 text

    src/index.js import PlayerObject from './PlayerObject.js' var player = new PlayerObject(5, 5) window.addEventListener('load', () => { document.querySelector('body').innerHTML = `

    Player position x = ${player.x}, y = ${player.y}` }) ES2015 modules

    Slide 143

    Slide 143 text

    src/PlayerObject.js class PlayerObject { constructor (x, y) { this.x = x this.y = y } } export default PlayerObject

    Slide 144

    Slide 144 text

    Packaging all into one • By using one command you can package these file into one • node ./node_modules/webpack/bin/webpack.js src/index.js

    Slide 145

    Slide 145 text

    Web Apis Canvas API, Web Workers, Web Storage, Geolocation ..

    Slide 146

    Slide 146 text

    Canvas API • In HTML5 element can be used to draw graphics via scripting in JavaScript • Draw graphics, bitmaps, create animations... • Really easy • • And then in JS start to draw to the element

    Slide 147

    Slide 147 text

    Example var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); ctx.fillStyle = 'rgb(200, 0, 0)'; ctx.fillRect(10, 10, 50, 50);

    Slide 148

    Slide 148 text

    Implementing a Game // What keys are down let keysDown = new Set() // For drawing let ctx let canvas // Game object let x = 50 let y = 50

    Slide 149

    Slide 149 text

    function init () { canvas = document.querySelector('canvas') ctx = canvas.getContext('2d') canvas.width = window.innerWidth canvas.height = window.innerHeight window.addEventListener('keydown', (event) => { keysDown.add(event.keyCode) }) window.addEventListener('keyup', (event) => { keysDown.clear(event.keyCode) }) window.requestAnimationFrame(gameloop); } window.addEventListener('load', (event) => { init() })

    Slide 150

    Slide 150 text

    function gameloop() { ctx.fillStyle = 'rgb(255, 255, 255, 1)' ctx.fillRect(0, 0, canvas.width, canvas.height) ctx.fillStyle = 'rgb(0,0,0)' ctx.fillRect(x, y, 50, 50) moveObjects() window.requestAnimationFrame(gameloop); }

    Slide 151

    Slide 151 text

    function moveObjects() { const Direction = {UP: 87, DOWN: 83, LEFT: 65, RIGHT: 68} if (keysDown.has(Direction.UP)) { y-- } if (keysDown.has(Direction.DOWN)) { y++ } if (keysDown.has(Direction.LEFT)) { x-- } if (keysDown.has(Direction.RIGHT)) { x++ } }

    Slide 152

    Slide 152 text

    Geolocation Example navigator.geolocation.getCurrentPosition((position) => { console.log(position.coords.latitude) console.log(position.coords.longitude) });

    Slide 153

    Slide 153 text

    FileReader

    File:

    function read(e) { let text = e.target.result console.log(text) } function readFile(file) { var reader = new FileReader(); reader.onload = read reader.readAsText(file) } function handleFileSelect(evt) { let f = evt.target.files[0] readFile(f) } document.getElementById('files').addEventListener('change', handleFileSelect);

    Slide 154

    Slide 154 text

    Others • Web Workers • For threading • Web Storage • Store data inside of browser • FileReader • To read files • Drag and Drop • Dragging and dropping elements