Module 5 – JavaScript, , and jQuery

• Module 5 Contains an Individual and Group component – Both are due on Wednesday Oct 23rd – Start early on this module – One of the most time consuming modules in the course

• Read the WIKI before starting along with a few JavaScript and jQuery tutorials

1Extensible- CSE 330 – Creative Networking Programming Platform and Rapid Prototyping 1

Module 5

• JavaScript – Scripting language to add interactivity to HTML pages – Java and JavaScript are completely different languages

• AJAX – Asynchronous JavaScript and XML (AJAX) – Allows for retrieval of data from web servers in the background

• jQuery – JavaScript library

2Extensible- CSE 330 – Creative Networking Programming Platform and Rapid Prototyping 2 JavaScript

• Popular scripting language widely supported in browsers to add interaction – Pop-Up Windows – User Input Forms – Calculations – Special Effects

• Implementation of the ECMAScript language

3Extensible- CSE 330 – Creative Networking Programming Platform and Rapid Prototyping 3

JavaScript

• JavaScript is a prototyped-based scripting language – Dynamic, weakly typed

• Interpreted language – You do not compile it

• Uses prototypes instead of classes for inheritance

4Extensible- CSE 330 – Creative Networking Programming Platform and Rapid Prototyping 4 Is JavaScript like Java?

• Java and JavaScript are similar like Car and Carpet are similar

• Two completely different languages with different concepts – Java is compiled, JavaScript is interpreted – Java is object-oriented, JavaScript is prototyped based – Java requires strict typing, JavaScript allows for dynamic typing

5Extensible- CSE 330 – Creative Networking Programming Platform and Rapid Prototyping 5

JavaScript Basics

• Declare a variable with let let foo = “JS is fun”;

• Declare a constant with const const bar = ”This is will not change”;

• Older versions of JavaScript do not support let and const and use var instead – In this course we will use let and const and avoid using var

• Define a function with function function foo() { //Some JS code here }

• Functions are also objects

6Extensible- CSE 330 – Creative Networking Programming Platform and Rapid Prototyping 6 Writing a JavaScript Program

• JavaScript programs can either be placed – directly into the HTML file or – can be saved in external files

• You can place JavaScript anywhere within the HTML file: within – the tags or – the tags

7Extensible- CSE 330 – Creative Networking Programming Platform and Rapid Prototyping 7

Using the – SRC property is required only if you place your program in a separate file

• Older versions of HTML (before 5) use a slightly different format –

9Extensible- CSE 330 – Creative Networking Programming Platform and Rapid Prototyping 9

JavaScript Example (part 2)

form.text1.value)">

10Extensible- CSE 330 – CreativeNetworking Programming Platform and Rapid Prototyping 10 JavaScript Example My JavaScript Example

11Extensible- CSE 330 – CreativeNetworking Programming Platform and Rapid Prototyping 11

JavaScript Event Listeners

• We can control events in a more granular way using Event Listeners

• Event Listeners allow for custom behavior for every element

document.getElementById("hello").addEventListener("click",MsgBox, false);

12Extensible- CSE 330 – CreativeNetworking Programming Platform and Rapid Prototyping 12 JavaScript Additional Information

• The CSE 330 Wiki provides a great intro into JavaScript along with some excellent links to more comprehensive tutorials

• Additional JS tutorials – http://www.quirksmode.org/js/contents.html – ://docs.webplatform.org/wiki/Meta:javascript/t utorials

13Extensible- CSE 330 – CreativeNetworking Programming Platform and Rapid Prototyping 13

JavaScript Debugging

• JSHint is a great resources to help debug your code – http://www.jshint.com/

• Tools for browsers also exist – extension – Chrome and • Webkit Inspector comes bundled with the browser

14Extensible- CSE 330 – CreativeNetworking Programming Platform and Rapid Prototyping 14 JavaScript Examples

http://research.engineering.wustl.edu/~todd/cse330/demo/lecture5/

15Extensible- CSE 330 – CreativeNetworking Programming Platform and Rapid Prototyping 15

AJAX

• Stands for Asynchronous JavaScript and XML”

• Development technique for creating interactive web applications

• Not a new Technology but more of a Pattern

16Extensible- CSE 330 – CreativeNetworking Programming Platform and Rapid Prototyping 16 Motivation for AJAX

• Web pages always RELOAD and never get UPDATED

• Users wait for the entire page to load even if a single piece of data is needed

• Single request/response restrictions

17Extensible- CSE 330 – CreativeNetworking Programming Platform and Rapid Prototyping 17

Components

– HTML (or XHTML) and CSS • Presenting information

• Dynamic display and interaction with the information

– XMLHttpRequest object • Retrieving data ASYNCHRONOUSLY from the .

– JavaScript • Binding everything together

18Extensible- CSE 330 – CreativeNetworking Programming Platform and Rapid Prototyping 18 The DOM

• Document Object Model (DOM): platform- and language-independent way to represent XML – Adopts a tree-based representation – W3C standard, supported by modern browsers

• JavaScript uses DOM to manipulate content – To process user events – To process server responses (via XMLHttpRequest)

19Extensible- CSE 330 – CreativeNetworking Programming Platform and Rapid Prototyping 19

The DOM

• Unlike other programming languages, JavaScript understands HTML and can directly access it

• JavaScript uses the HTML Document Object Model to manipulate HTML

• The DOM is a hierarchy of HTML things

• Use the DOM to build an address to refer to HTML elements in a

• Levels of the DOM are dot-separated in the syntax

20Extensible- CSE 330 – CreativeNetworking Programming Platform and Rapid Prototyping 20 DOM

21Extensible- CSE 330 – CreativeNetworking Programming Platform and Rapid Prototyping 21

Accessing the DOM Example

https://research.engineering.wustl.edu/~todd/cse330/demo/lecture5/

22Extensible- CSE 330 – CreativeNetworking Programming Platform and Rapid Prototyping 22 and AJAX

23Extensible- CSE 330 – CreativeNetworking Programming Platform and Rapid Prototyping 23

Request Processing

24Extensible- CSE 330 – CreativeNetworking Programming Platform and Rapid Prototyping 24 Asynchronous processing - XMLHttpRequest

• Allows to execute an HTTP request in background

• Callbacks kick back into JavaScript Code

• Supported in all standard browsers

25Extensible- CSE 330 – CreativeNetworking Programming Platform and Rapid Prototyping 25

Using XMLHttpRequest

• First you must create the XMLHttpRequest Object in JavaScript

• Example – const xmlHttp = new XMLHttpRequest();

• Older browsers might require different syntax – For example ( versions <9) • const xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); – We will not worry about JS compatibility with IE < 9 in this course

26Extensible- CSE 330 – CreativeNetworking Programming Platform and Rapid Prototyping 26 Using XMLHttpRequest

• Transferring data to Server – Open() to initialize connection to Server – Send() to send the actual Data

• Example (POST) – xmlHttp.open("POST", "/query.cgi”,true); – xmlHttp.send("[email protected]");

• Example (GET) – xmlHttp.open("GET","hello.txt",true); – xmlHttp.send(null);

27Extensible- CSE 330 – CreativeNetworking Programming Platform and Rapid Prototyping 27

What happens after sending data?

• XMLHttpRequest contacts the server and retrieves the data – Can take indeterminate amount of time

• Create an Event Listener to determine when the object has finished loading with the data we are interested in – Specifically listen for the load event to occur

28Extensible- CSE 330 – CreativeNetworking Programming Platform and Rapid Prototyping 28 Events of interest

xmlHttp.addEventListener("load”,myCallbackFunction,false);

29Extensible- CSE 330 – CreativeNetworking Programming Platform and Rapid Prototyping 29

Using XMLHttpRequest

• Parse and display data – responseXML • DOM-structured object – responseText • One complete string • Examples – const nameNode = requester.responseXML.getElementsByTagName("name")[0];

– const nameTextNode = nameNode.childNodes[0]; • From an event function myCallback(event) { alert(“The response “ + event.target.responseText); }

30Extensible- CSE 330 – CreativeNetworking Programming Platform and Rapid Prototyping 30 AJAX Example

31Extensible- CSE 330 – CreativeNetworking Programming Platform and Rapid Prototyping 31

Interaction between Components

32Extensible- CSE 330 – CreativeNetworking Programming Platform and Rapid Prototyping 32 AJAX Example

33Extensible- CSE 330 – CreativeNetworking Programming Platform and Rapid Prototyping 33

Promises • A promise is an object representing the eventual completion or failure of an asynchronous operation

• Promises are returned objects that you attached callbacks to

• A promise can only succeed or fail

• This promise resolves to the response of that request, whether it is successful or not.

34Extensible- CSE 330 – CreativeNetworking Programming Platform and Rapid Prototyping 34 Creating and Using Promises

• The promise constructor takes one argument – A callback with two parameters, resolve and reject.

const promise = new Promise(function resolve, reject) {

//do something

if ( /* everything works */ ) { resolve("it works"); } else { reject(Error("It did not work")); } }); • To execute the callback:

promise.then(function(result) { console.log(result); //worked }, function(err) { console.log(err); //Error :It broke }); • The then() takes two arguments – A callback for success and one for failure, both are optional.

35Extensible- CSE 330 – CreativeNetworking Programming Platform and Rapid Prototyping 35

Fetch API

• Newer API that provides mechanism to asynchronously access resources across the network

• Fetch takes one argument – The link to the resources • Fetch returns a promise – Which resolves to the Response Object

• Similar to XMLHttpRequest but with a fairly simple syntax

36Extensible- CSE 330 – CreativeNetworking Programming Platform and Rapid Prototyping 36 Fetch API • fetch() has one required argument (the path to the resource) – It returns a promise – This promise resolves to the response of that request, whether it is successful or not.

fetch() .then(function(response) { // Do stuff with response }) .catch(function(error) { console.log(" Found an error" + error); });

37Extensible- CSE 330 – CreativeNetworking Programming Platform and Rapid Prototyping 37

Fetch Example

38Extensible- CSE 330 – CreativeNetworking Programming Platform and Rapid Prototyping 38 Additional Links for Promise and Fetch

• https://developers.google.com/web/fundamentals/primers/p romises

• https://developer.mozilla.org/en- US/docs/Web/JavaScript/Guide/Using_promises

• https://developer.mozilla.org/en- US/docs/Web/API/Fetch_API

39Extensible- CSE 330 – CreativeNetworking Programming Platform and Rapid Prototyping 39

jQuery – Simplify your JavaScript

40Extensible- CSE 330 – CreativeNetworking Programming Platform and Rapid Prototyping 40 What is jQuery? • A framework for Client Side JavaScript

• Frameworks provide useful alternatives for common programming tasks, creating functionality which may not be available or cumbersome to use within a language.

• An open source project, maintained by a group of developers, with a very active support base and thorough, well written documentation.

41Extensible- CSE 330 – CreativeNetworking Programming Platform and Rapid Prototyping 41

What jQuery is not…

• A substitute for knowing JavaScript – jQuery is extraordinarily useful, but you should still know how JavaScript works and how to use it correctly. This means more than Googling a tutorial and calling yourself an expert.

• A solve all – There is still plenty of functionality built into JavaScript that should be utilized! Dont turn every project into a quest to jQuery-ize the problem, use jQuery where it makes sense. Create solutions in environments where they belong.

42Extensible- CSE 330 – CreativeNetworking Programming Platform and Rapid Prototyping 42 What is available with jQuery? • Cross browser support • JavaScript animation and detection • Hundreds of plugins for • AJAX functions pre-built user • CSS functions interfaces, advanced • DOM manipulation animations, form • DOM transversal validation, etc • Attribute manipulation • Expandable • Event detection and functionality using handling custom plugins • Small foot print

43Extensible- CSE 330 – CreativeNetworking Programming Platform and Rapid Prototyping 43

The jQuery/$ Object

• Represented by both $ and jQuery – To use jQuery only, use jQuery.noConflict(), for other frameworks that use $

• By default,$ represents the jQuery object. When combined with a selector, can represent multiple DOM Elements

• Used with all jQuery functions.

44Extensible- CSE 330 – CreativeNetworking Programming Platform and Rapid Prototyping 44 jQuery Examples

• jQuery basic syntax $(selector).action()

• $ sign used to access jQuery • Selector “finds” the HTML element(s) • An action is performed on the element(s)

• Examples – $(this).hide() //hides current element – $(“p”).hide() //hides all

elements – $(“.test”).hide() //hides all elements with class=“test” – $(“#test”).hide() //hides the element with id=“test”

45Extensible- CSE 330 – CreativeNetworking Programming Platform and Rapid Prototyping 45

jQuery & AJAX • jQuery has a series of functions which provide a common interface for AJAX, no matter what browser you are using

• Most of the upper level AJAX functions have a common layout: – $.func(url[,params][,callback]), [ ] optional • url: string representing server target • params: names and values to send to server • callback: function executed on successful communication.

46Extensible- CSE 330 – CreativeNetworking Programming Platform and Rapid Prototyping 46 jQuery AJAX Functions

• $.func(url[,params][,callback]) • $.ajax, $.ajaxSetup – $.get – async – $.getJSON – beforeSend – $.getIfModified – complete – $.getScript – contentType – $. – data – dataType • $(selector), inject HTML – error – load – global – loadIfModified – ifModified – processData • $(selector), ajaxSetup alts – success – ajaxComplete – timeout – ajaxError – type – ajaxSend – url – ajaxStart – ajaxStop – ajaxSuccess

47Extensible- CSE 330 – CreativeNetworking Programming Platform and Rapid Prototyping 47

Example – Show/Hide the old way

Click here to toggle visibility of #foo

function toggle_visibility(id) { const e = document.getElementById(id); if(e.style.display == 'block') e.style.display = 'none'; else e.style.display = 'block'; }

48Extensible- CSE 330 – CreativeNetworking Programming Platform and Rapid Prototyping 48 Example – Show/Hide with jQuery

$().ready(function(){ $("a").click(function(){ $("#more").toggle("slow"); return false; }); });

49Extensible- CSE 330 – CreativeNetworking Programming Platform and Rapid Prototyping 49

Example – Ajax the old way

function GetXmlHttpObject(handler) { let objXmlHttp = null; //Holds the local xmlHTTP object instance

//Depending on the browser, try to create the xmlHttp object if (is_ie){ var strObjName = (is_ie5) ? '.XMLHTTP' : 'Msxml2.XMLHTTP'; try{ objXmlHttp = new ActiveXObject(strObjName); objXmlHttp.onreadystatechange = handler; } catch(e){ //Object creation errored alert('Verify that activescripting and activeX controls are enabled'); return; } } else{ // Mozilla | | Safari objXmlHttp = new XMLHttpRequest(); objXmlHttp.onload = handler; objXmlHttp.onerror = handler; } //Return the instantiated object return objXmlHttp; }

50Extensible- CSE 330 – CreativeNetworking Programming Platform and Rapid Prototyping 50 Example – Ajax with jQuery

$.get("update_actions.aspx", {st: "yes", f: $(this).attr("ID")} );

51Extensible- CSE 330 – CreativeNetworking Programming Platform and Rapid Prototyping 51

jQuery Examples

52Extensible- CSE 330 – CreativeNetworking Programming Platform and Rapid Prototyping 52 Calendar Examples

53Extensible- CSE 330 – CreativeNetworking Programming Platform and Rapid Prototyping 53