Extensible Networking Platform 11 - CSE 330 – Creative Programming and Rapid Prototyping
Module 5 – JavaScript, AJAX, and jQuery
• Module 5 Contains an Individual and Group component– Both are due on Wednesday March 18th– 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
1
Extensible Networking Platform 22 - CSE 330 – Creative Programming and Rapid Prototyping
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
2
Extensible Networking Platform 33 - CSE 330 – Creative Programming and Rapid Prototyping
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
3
Extensible Networking Platform 44 - CSE 330 – Creative Programming and Rapid Prototyping
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
4
Extensible Networking Platform 55 - CSE 330 – Creative Programming and Rapid Prototyping
Is JavaScript like Java?
• Java and JavaScript are similar likeCar 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
5
Extensible Networking Platform 66 - CSE 330 – Creative Programming and Rapid Prototyping
JavaScript Basics• Declare a variable with let
let foo = “JS is fun”;
• Declare a constant with constconst 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 functionfunction foo() {
//Some JS code here}
• Functions are also objects
6
Extensible Networking Platform 77 - CSE 330 – Creative Programming and Rapid Prototyping
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 <HEAD> tags or– the <BODY> tags
7
Extensible Networking Platform 88 - CSE 330 – Creative Programming and Rapid Prototyping
Using the <SCRIPT> Tag
<script src=“url”></script>– SRC property is required only if you place your
program in a separate file
<script> script commands and comments
</script>
• Older versions of HTML (before 5) use a slightly different format – <script type=“text/javascript”> – This is no longer necessary, simply use <script>
8
Extensible Networking Platform 99 - CSE 330 – Creative Programming and Rapid Prototyping
JavaScript Example (part 1)
<!DOCTYPE html><html><head><title>My JavaScript Example</title>
<script>function MsgBox(textstring) {
alert(textstring);}
</script>
9
Extensible Networking Platform 1010 - CSE 330 – Creative Programming and Rapid Prototyping
JavaScript Example (part 2)
<body><form><input type = "text" name ="text1" ><input type = "submit" value ="Show Me"
onClick="MsgBox(form.text1.value)"></form></body>
</html>
10
Extensible Networking Platform 1111 - CSE 330 – Creative Programming and Rapid Prototyping
JavaScript Example<!DOCTYPE html> <html lang="en"><head><title>My JavaScript Example</title>
<script>function MsgBox(textstring) {
alert(textstring);}</script> </head>
<body><form><input type = "text" name ="text1" ><input type = "submit" value ="Show Me"
onClick="MsgBox(form.text1.value)"></form></body>
</html>
11
Extensible Networking Platform 1212 - CSE 330 – Creative Programming and Rapid Prototyping
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);
12
Extensible Networking Platform 1313 - CSE 330 – Creative Programming and Rapid Prototyping
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– https://docs.webplatform.org/wiki/Meta:javascript/t
utorials
13
Extensible Networking Platform 1414 - CSE 330 – Creative Programming and Rapid Prototyping
JavaScript Debugging
• JSHint is a great resources to help debug your code– http://www.jshint.com/
• Tools for browsers also exist– Firefox
• Firebug extension– Chrome and Safari
• Webkit Inspector comes bundled with the browser
14
Extensible Networking Platform 1515 - CSE 330 – Creative Programming and Rapid Prototyping
JavaScript Examples
http://research.engineering.wustl.edu/~todd/cse330/demo/lecture5/
15
Extensible Networking Platform 1616 - CSE 330 – Creative Programming and Rapid Prototyping
AJAX
• Stands for “Asynchronous JavaScript and XML”
• Development technique for creating interactive web applications
• Not a new Technology but more of a Pattern
16
Extensible Networking Platform 1717 - CSE 330 – Creative Programming and Rapid Prototyping
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
17
Extensible Networking Platform 1818 - CSE 330 – Creative Programming and Rapid Prototyping
Components
– HTML (or XHTML) and CSS • Presenting information
– Document Object Model • Dynamic display and interaction with the information
– XMLHttpRequest object • Retrieving data ASYNCHRONOUSLY from the web server.
– JavaScript• Binding everything together
18
Extensible Networking Platform 1919 - CSE 330 – Creative Programming and Rapid Prototyping
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)
19
Extensible Networking Platform 2020 - CSE 330 – Creative Programming and Rapid Prototyping
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 web page
• Levels of the DOM are dot-separated in the syntax
20
Extensible Networking Platform 2121 - CSE 330 – Creative Programming and Rapid Prototyping
DOM
21
Extensible Networking Platform 2222 - CSE 330 – Creative Programming and Rapid Prototyping
Accessing the DOM Example
https://research.engineering.wustl.edu/~todd/cse330/demo/lecture5/
22
Extensible Networking Platform 2323 - CSE 330 – Creative Programming and Rapid Prototyping
Web Application and AJAX
23
Extensible Networking Platform 2424 - CSE 330 – Creative Programming and Rapid Prototyping
Request Processing
24
Extensible Networking Platform 2525 - CSE 330 – Creative Programming and Rapid Prototyping
Asynchronous processing - XMLHttpRequest
• Allows to execute an HTTP request in background
• Callbacks kick back into JavaScript Code
• Supported in all standard browsers
25
Extensible Networking Platform 2626 - CSE 330 – Creative Programming and Rapid Prototyping
Using XMLHttpRequest
• First you must create the XMLHttpRequest Object in JavaScript
• Example– const xmlHttp = new XMLHttpRequest();
• Older browsers might require different syntax– For example (Internet Explorer versions <9)
• const xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); – We will not worry about JS compatibility with IE < 9 in this course
26
Extensible Networking Platform 2727 - CSE 330 – Creative Programming and Rapid Prototyping
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("name=Bob&[email protected]");
• Example (GET)– xmlHttp.open("GET","hello.txt",true);– xmlHttp.send(null);
27
Extensible Networking Platform 2828 - CSE 330 – Creative Programming and Rapid Prototyping
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
28
Extensible Networking Platform 2929 - CSE 330 – Creative Programming and Rapid Prototyping
Events of interest
xmlHttp.addEventListener("load”,myCallbackFunction,false);
29
Extensible Networking Platform 3030 - CSE 330 – Creative Programming and Rapid Prototyping
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);}
30
Extensible Networking Platform 3131 - CSE 330 – Creative Programming and Rapid Prototyping
AJAX Example
<script>
const xmlHttp = new XMLHttpRequest();xmlHttp.open("GET","hello.txt",true);xmlHttp.addEventListener("load”,myCallback,false);xmlHttp.send(null);
function myCallback(event) {alert(“The response “ + event.target.responseText);}
</script>
31
Extensible Networking Platform 3232 - CSE 330 – Creative Programming and Rapid Prototyping
Interaction between Components
32
Extensible Networking Platform 3333 - CSE 330 – Creative Programming and Rapid Prototyping
AJAX Example
33
Extensible Networking Platform 3434 - CSE 330 – Creative Programming and Rapid Prototyping
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.
34
Extensible Networking Platform 3535 - CSE 330 – Creative Programming and Rapid Prototyping
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.
35
Extensible Networking Platform 3636 - CSE 330 – Creative Programming and Rapid Prototyping
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
36
Extensible Networking Platform 3737 - CSE 330 – Creative Programming and Rapid Prototyping
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(url).then(function(response) {
// Do stuff with response}).catch(function(error) {
console.log(" Found an error" + error);});
37
Extensible Networking Platform 3838 - CSE 330 – Creative Programming and Rapid Prototyping
Fetch Example
38
Extensible Networking Platform 3939 - CSE 330 – Creative Programming and Rapid Prototyping
Additional Links for Promise and Fetch
• https://developers.google.com/web/fundamentals/primers/promises
• https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises
• https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
39
Extensible Networking Platform 4040 - CSE 330 – Creative Programming and Rapid Prototyping
jQuery – Simplify your JavaScript
40
Extensible Networking Platform 4141 - CSE 330 – Creative Programming and Rapid Prototyping
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.
41
Extensible Networking Platform 4242 - CSE 330 – Creative Programming and Rapid Prototyping
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! Don’t turn every project into a quest to ‘jQuery-ize’ the problem, use jQuery where it makes sense. Create solutions in environments where they belong.
42
Extensible Networking Platform 4343 - CSE 330 – Creative Programming and Rapid Prototyping
What is available with jQuery?
• Cross browser support and detection
• AJAX functions• CSS functions• DOM manipulation• DOM transversal• Attribute manipulation• Event detection and
handling
• JavaScript animation• Hundreds of plugins for
pre-built user interfaces, advanced animations, form validation, etc
• Expandable functionality using custom plugins
• Small foot print
43
Extensible Networking Platform 4444 - CSE 330 – Creative Programming and Rapid Prototyping
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.
44
Extensible Networking Platform 4545 - CSE 330 – Creative Programming and Rapid Prototyping
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 <p> elements– $(“.test”).hide() //hides all elements with class=“test”– $(“#test”).hide() //hides the element with id=“test”
45
Extensible Networking Platform 4646 - CSE 330 – Creative Programming and Rapid Prototyping
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.
46
Extensible Networking Platform 4747 - CSE 330 – Creative Programming and Rapid Prototyping
jQuery AJAX Functions
• $.func(url[,params][,callback])– $.get– $.getJSON– $.getIfModified– $.getScript– $.post
• $(selector), inject HTML– load– loadIfModified
• $(selector), ajaxSetup alts– ajaxComplete– ajaxError– ajaxSend– ajaxStart– ajaxStop– ajaxSuccess
• $.ajax, $.ajaxSetup– async– beforeSend– complete– contentType– data– dataType– error– global– ifModified– processData– success– timeout– type– url
47
Extensible Networking Platform 4848 - CSE 330 – Creative Programming and Rapid Prototyping
Example – Show/Hide the old way
<a href="#" onclick="toggle_visibility('foo');">Click here to toggle visibility of #foo</a>
function toggle_visibility(id) {const e = document.getElementById(id);if(e.style.display == 'block')
e.style.display = 'none';else
e.style.display = 'block';}
48
Extensible Networking Platform 4949 - CSE 330 – Creative Programming and Rapid Prototyping
Example – Show/Hide with jQuery
$().ready(function(){$("a").click(function(){
$("#more").toggle("slow");return false;
});});
49
Extensible Networking Platform 5050 - CSE 330 – Creative Programming and Rapid Prototyping
Example – Ajax the old wayfunction 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) ? 'Microsoft.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 | Netscape | Safari objXmlHttp = new XMLHttpRequest(); objXmlHttp.onload = handler; objXmlHttp.onerror = handler;
} //Return the instantiated object return objXmlHttp;
}
50
Extensible Networking Platform 5151 - CSE 330 – Creative Programming and Rapid Prototyping
Example – Ajax with jQuery
$.get("update_actions.aspx", {st: "yes", f: $(this).attr("ID")} );
51
Extensible Networking Platform 5252 - CSE 330 – Creative Programming and Rapid Prototyping
jQuery Examples
52