diff --git a/LectureCodeExamples/Week4/JSObjectsFetchCode/AddingProperties.html b/LectureCodeExamples/Week4/JSObjectsFetchCode/AddingProperties.html new file mode 100755 index 0000000000000000000000000000000000000000..168b0b7906f00bfe01ad5a1303f3210f601d2d58 --- /dev/null +++ b/LectureCodeExamples/Week4/JSObjectsFetchCode/AddingProperties.html @@ -0,0 +1,37 @@ +<!DOCTYPE html> +<html lang="en"> + <head> + <meta charset="utf-8"> + <title>Adding Properties</title> + </head> + + <body> + <script> + "use strict"; + + let sale = {}; + do { + let item = prompt("Enter name of item you want to buy."); + let numberOfItems = Number(prompt("Enter number of items you want to buy")); + + /* Adding property */ + if (sale[item] === undefined) { // IMPORTANT: Otherwise will remove previous value + sale[item] = numberOfItems; + } else { + sale[item] += numberOfItems; + } + + if (!window.confirm("Do you want to buy another item?")) { + break; + } + } while (true); + + /* Report about bought items */ + let report = "Items bought\n"; + for (let propertyName in sale) { + report += propertyName + "-->" + sale[propertyName] + "\n"; + } + alert(report); + </script> + </body> +</html> diff --git a/LectureCodeExamples/Week4/JSObjectsFetchCode/Destructuring.html b/LectureCodeExamples/Week4/JSObjectsFetchCode/Destructuring.html new file mode 100755 index 0000000000000000000000000000000000000000..45998804ccc2237115a9dbe03e0522d79125a911 --- /dev/null +++ b/LectureCodeExamples/Week4/JSObjectsFetchCode/Destructuring.html @@ -0,0 +1,64 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> + <meta charset="utf-8"> + <title>JS Destructuring Example</title> +</head> + +<body> + <script> + "use strict"; + + main(); + + function main() { + /* Destructuring arrays */ + let names = ["Andrew", "Karl", "Olivia"]; + let [first, second] = names; + document.writeln("Original Array: " + names + "<br>"); + document.writeln("First: " + first + "<br>" + "Second: " + second + "<br><br>"); + + document.writeln("***** Destructuring Object *****<br>"); + /* Destructuring object */ + let app = { + name: "mapApp", + developed: 1986, + location: "CP" + }; + /* You must use the same property name; try name2 instead of name + You don't need to retrieve all properties (convenient for objects + with several properties) + */ + let { + name, + developed + } = app; /* Notice using { } */ + document.writeln("Name: " + name + ", " + "Developed: " + developed + "<br><br>"); + + document.writeln("***** Destructuring Object in Function Call *****<br>"); + myFunc(app); /* function call */ + function myFunc({developed}){ + document.writeln("In Function: developed: " + developed + "<br><br>"); + } + + document.writeln("***** Destructuring Object in Function Call *****<br>"); + /* function call */ + myFunc2(app); + + /* Using a property name different than original */ + function myFunc2({name: yourName}){ + document.writeln("YourName: " + yourName + "<br><br>"); + } + + document.writeln("***** Swapping Values *****<br>"); + /* swap */ + let a = 100, + b = 200; + [b, a] = [a, b]; + document.writeln(a + ", " + b + "<br>"); + } + </script> +</body> + +</html> \ No newline at end of file diff --git a/LectureCodeExamples/Week4/JSObjectsFetchCode/FetchExamples/AsyncAwait.html b/LectureCodeExamples/Week4/JSObjectsFetchCode/FetchExamples/AsyncAwait.html new file mode 100755 index 0000000000000000000000000000000000000000..2415ec6fa0bc33e1392754469485069e649b94e6 --- /dev/null +++ b/LectureCodeExamples/Week4/JSObjectsFetchCode/FetchExamples/AsyncAwait.html @@ -0,0 +1,30 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> + <title>Example</title> + <meta charset="utf-8"> +</head> + +<body> + <script> + + process(); + + async function process() { + let url = "https://jsonplaceholder.typicode.com/todos/1"; // Notice the 1 at the end + alert(`Retrieving data from ${url} (check console for results)`); + + const response = await fetch(url); + console.log("Response"); + console.log(response); + + const json = await response.json(); + console.log("Json"); + console.log(json); + console.log("***** END OF SCRIPT *****"); // Check WHERE this message appears in the console + } + </script> +</body> + +</html> \ No newline at end of file diff --git a/LectureCodeExamples/Week4/JSObjectsFetchCode/FetchExamples/Cors.html b/LectureCodeExamples/Week4/JSObjectsFetchCode/FetchExamples/Cors.html new file mode 100755 index 0000000000000000000000000000000000000000..dc34b7e5f4103696e84f6bc9ee3fb995533e9d9a --- /dev/null +++ b/LectureCodeExamples/Week4/JSObjectsFetchCode/FetchExamples/Cors.html @@ -0,0 +1,33 @@ +<!DOCTYPE html> +<html lang="en"> + <head> + <meta charset="UTF-8" /> + <meta name="viewport" content="width=device-width, initial-scale=1.0" /> + <title>TAs Info</title> + </head> + + <body> + <h3>CORS</h3> + <p> + Try running this example by first opening this file using Live Server and + then by right-clicking on the file and selecting the Chrome browser. + </p> + <div id="display"></div> + <script> + async function readTAsInfo() { + const filename = "./tas.json"; + const response = await fetch(filename); + const data = await response.json(); + let table = ""; + data.forEach((entry) => { + table += `<tr><td>${entry.name}</td><td>${entry.course}</td></tr>`; + }); + const tableHeadSection = `<table border='1'><tr><th>Name</th><th>Course</th></tr>`; + table = `${tableHeadSection}${table}</table>`; + document.querySelector("#display").innerHTML = table; + } + + readTAsInfo(); + </script> + </body> +</html> diff --git a/LectureCodeExamples/Week4/JSObjectsFetchCode/FetchExamples/DisplayingCats.html b/LectureCodeExamples/Week4/JSObjectsFetchCode/FetchExamples/DisplayingCats.html new file mode 100755 index 0000000000000000000000000000000000000000..f09a93b6bf2c010853ee8a5d6421206e6de4e07b --- /dev/null +++ b/LectureCodeExamples/Week4/JSObjectsFetchCode/FetchExamples/DisplayingCats.html @@ -0,0 +1,48 @@ +<!DOCTYPE html> +<html lang="en"> + <head> + <meta charset="utf-8"> + <title>Displaying cats</title> + </head> + + <body> + <h1>Cat Images</h1> + + <label>Animation speed in milliseconds <input id="speed" type="text" value="1000"></label><br><br> + <input type="button" value="Start Displaying Cats" onclick="startAnimation()"> + <input type="button" value="Stop Animation" onclick="stopAnimation()"><br><br> + <img id="downloadedImage" src="doesnotexistyet.png" height="300" alt="image"><br> + <div id="display"></div> + + <script> + let animationId, animationStarted = false; + + function downloadCatImage() { + let catImagesUrl = `https://api.thecatapi.com/v1/images/search`; + fetch(catImagesUrl) + .then(response => response.json()) + .then(json => { + const imageUrl = json[0].url; + const img = document.querySelector("#downloadedImage"); + img.src = imageUrl; + document.querySelector("#display").innerHTML = `Source: <a href="${imageUrl}">${imageUrl}</a>`; + }); + } + + function startAnimation() { + if (!animationStarted) { /* Preventing executing setInterval multiple times before stopping animation */ + let intervalInMillisecs = document.querySelector("#speed").value; + animationId = setInterval(downloadCatImage, intervalInMillisecs); + animationStarted = true; + } + } + + function stopAnimation() { + if (animationStarted) { + clearInterval(animationId); + animationStarted = false; + } + } + </script> + </body> +</html> diff --git a/LectureCodeExamples/Week4/JSObjectsFetchCode/FetchExamples/FetchingImage.html b/LectureCodeExamples/Week4/JSObjectsFetchCode/FetchExamples/FetchingImage.html new file mode 100755 index 0000000000000000000000000000000000000000..7b7fddb5e3484fe477ea97c47204077c810492a8 --- /dev/null +++ b/LectureCodeExamples/Week4/JSObjectsFetchCode/FetchExamples/FetchingImage.html @@ -0,0 +1,27 @@ +<!DOCTYPE html> +<html lang="en"> + <head> + <meta charset="utf-8"> + <title>Fetching Image</title> + </head> + + <body> + <h1>Fetching Random Cat Image</h1> + <input type="button" value="DownloadCatImage" onclick="downloadCatImage()"><br><br> + <img src="toPacifyHTMLValidator" id="downloadedImage" height="300" alt="catImg"><br> + + <script> + function downloadCatImage() { + let catImageUrl = `https://api.thecatapi.com/v1/images/search`; + fetch(catImageUrl) + .then(response => response.json()) + .then(json => { + console.log(json); /* Take a look at the console */ + const imageUrl = json[0].url; + const img = document.querySelector("#downloadedImage"); + img.src = imageUrl; + }); + } + </script> + </body> +</html> diff --git a/LectureCodeExamples/Week4/JSObjectsFetchCode/FetchExamples/PromisesFetch1.html b/LectureCodeExamples/Week4/JSObjectsFetchCode/FetchExamples/PromisesFetch1.html new file mode 100755 index 0000000000000000000000000000000000000000..716b3e8bd78857ef5b483402a066369d636c3475 --- /dev/null +++ b/LectureCodeExamples/Week4/JSObjectsFetchCode/FetchExamples/PromisesFetch1.html @@ -0,0 +1,22 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> + <title>Example</title> + <meta charset="utf-8"> +</head> + +<body> + <script> + + let url = "https://jsonplaceholder.typicode.com/todos/1"; // Notice the 1 at the end + alert(`Retrieving data from ${url} (check console for results)`); + + const promise = fetch(url); + console.log(promise); + promise.then(response => {console.log(response); return response.json()}).then(json => console.log(json)); // Process json object by displaying on the console + console.log("***** END OF SCRIPT *****"); // Check WHERE this message appears in the console + </script> +</body> + +</html> \ No newline at end of file diff --git a/LectureCodeExamples/Week4/JSObjectsFetchCode/FetchExamples/PromisesFetch2.html b/LectureCodeExamples/Week4/JSObjectsFetchCode/FetchExamples/PromisesFetch2.html new file mode 100755 index 0000000000000000000000000000000000000000..d3d88a883e145cfddde191466659bccfbcac96d4 --- /dev/null +++ b/LectureCodeExamples/Week4/JSObjectsFetchCode/FetchExamples/PromisesFetch2.html @@ -0,0 +1,21 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> + <title>Example</title> + <meta charset="utf-8"> +</head> + +<body> + <script> + + let url = "https://jsonplaceholder.typicode.com/todos/1"; // Notice the 1 at the end + alert(`Retrieving data from ${url}`); + + fetch(url) // Get data + .then(response => response.text()) // Process response by retrieving text + .then(text => document.writeln(text)); // Displaying text + </script> +</body> + +</html> \ No newline at end of file diff --git a/LectureCodeExamples/Week4/JSObjectsFetchCode/FetchExamples/PromisesFetch3.html b/LectureCodeExamples/Week4/JSObjectsFetchCode/FetchExamples/PromisesFetch3.html new file mode 100755 index 0000000000000000000000000000000000000000..fbf34e28d517ab54376662efd648aa9c786f8f49 --- /dev/null +++ b/LectureCodeExamples/Week4/JSObjectsFetchCode/FetchExamples/PromisesFetch3.html @@ -0,0 +1,26 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> + <title>Example</title> + <meta charset="utf-8"> +</head> + +<body> + <script> + + let url = "https://jsonplaceholder.typicode.com/todos/2"; + alert(`Retrieving data from ${url} (check console for results)`); + + fetch(url).then(response => response.json()).then(json => processObject(json)); + + function processObject({userId, id, title}) { // Notice destructoring + console.log("Data Retrieved\n"); + console.log(`user Id: ${userId}`); + console.log(`id: ${id}`); + console.log(`title: ${title}`); + } + </script> +</body> + +</html> \ No newline at end of file diff --git a/LectureCodeExamples/Week4/JSObjectsFetchCode/FetchExamples/PromisesFetch4.html b/LectureCodeExamples/Week4/JSObjectsFetchCode/FetchExamples/PromisesFetch4.html new file mode 100755 index 0000000000000000000000000000000000000000..01e18a491018db79ad652448fe91d0a398493df1 --- /dev/null +++ b/LectureCodeExamples/Week4/JSObjectsFetchCode/FetchExamples/PromisesFetch4.html @@ -0,0 +1,35 @@ +<!DOCTYPE html> +<html lang="en"> + <head> + <title>Example</title> + <meta charset="utf-8" /> + </head> + + <body> + <script> + let url = "https://jsonplaceholder.typicode.com/todos/1"; // Replace 1 with invalid value to see catch effect + alert(`Retrieving data from ${url} (check console for results)`); + + fetch(url) + .then((response) => { + if (!response.ok) { + throw "Problem downloading"; + } else { + return response.json(); + } + }) + .then((json) => processObject(json)) + .catch((error) => console.log("Reporting error: " + error)); + + function processObject(json) { + console.log("Data Retrieved\n"); + console.log(json); + console.log("Accessing properties\n"); + console.log(`user Id: ${json.userId}`); + // throw "Faking an error took place"; // Uncomment to faking an error; will trigger catch above + console.log(`id: ${json.id}`); + console.log(`title: ${json.title}`); + } + </script> + </body> +</html> diff --git a/LectureCodeExamples/Week4/JSObjectsFetchCode/FetchExamples/PromisesFetch5.html b/LectureCodeExamples/Week4/JSObjectsFetchCode/FetchExamples/PromisesFetch5.html new file mode 100755 index 0000000000000000000000000000000000000000..0e402634cf7fe2b6f3ddf28cdda8c21cfcd0ccba --- /dev/null +++ b/LectureCodeExamples/Week4/JSObjectsFetchCode/FetchExamples/PromisesFetch5.html @@ -0,0 +1,29 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> + <title>Example</title> + <meta charset="utf-8"> +</head> + +<body> + <script> + let url = "https://jsonplaceholder.typicode.com/todos/"; // Now retrieving a lot of entries + alert(`Retrieving data from ${url} (check console for results)`); + + fetch(url) + .then(response => response.json()) + .then(arrayOfObjects => printTitles(arrayOfObjects)) + .catch(error => console.log("Reporting error: " + error)); + + function printTitles(arrayOfObjects) { + // Our response is an array of values + console.log("\n\n***** Titles Received *****\n"); + for (let entry of arrayOfObjects) { + console.log(entry.title); + } + } + </script> +</body> + +</html> \ No newline at end of file diff --git a/LectureCodeExamples/Week4/JSObjectsFetchCode/FetchExamples/tas.json b/LectureCodeExamples/Week4/JSObjectsFetchCode/FetchExamples/tas.json new file mode 100755 index 0000000000000000000000000000000000000000..d69cf6656ba8181ba203c4fb50f13ad75fe7a10f --- /dev/null +++ b/LectureCodeExamples/Week4/JSObjectsFetchCode/FetchExamples/tas.json @@ -0,0 +1,7 @@ +[ + {"name": "Pete", "course": "CMSC335"}, + {"name": "Rose", "course": "CMSC216"}, + {"name": "Michael", "course": "CMSC335"}, + {"name": "Laura", "course": "CMSC216"}, + {"name": "Kathleen", "course": "CMSC335"} +] \ No newline at end of file diff --git a/LectureCodeExamples/Week4/JSObjectsFetchCode/JSONExample.html b/LectureCodeExamples/Week4/JSObjectsFetchCode/JSONExample.html new file mode 100755 index 0000000000000000000000000000000000000000..fa17aed44e4b719c288b746ccf10a7c9f4d9ea35 --- /dev/null +++ b/LectureCodeExamples/Week4/JSObjectsFetchCode/JSONExample.html @@ -0,0 +1,57 @@ +<!DOCTYPE html> + +<html lang="en"> +<head> + <meta charset="utf-8"> + <title>JS JSON Example</title> + <style> + h2 {text-decoration: underline} + </style> +</head> + +<body> + <script> + "use strict"; + main(); + + function main() { + let obj = { + "name": "Mary", + "age": 45, + "salary": 20000.00, + "employed": true, + "boss": null, + "cars": ["toyota", "honda"], /* array example */ + "friends": [{ /* array of objects */ + "fname": "Peter" + }, { + "fname": "Rachel" + }] + }; + document.writeln("<h2>JSON String (After stringify Object)</h2>"); + let str = JSON.stringify(obj); + document.writeln(str); + + + document.writeln("<h2>After Parsing String</h2>") + let newObj = JSON.parse(str); + for (let prop in newObj) { + document.writeln(prop + "→" + newObj[prop] + "<br>"); + } + + + document.writeln("<h2>Check console to see object corresponding to following string</h2>"); + /* Using template literal */ + let secondObjStr = `{ + "school": "UMCP", + "zipCode": 20742 + }`; + document.writeln("String: " + secondObjStr + "<br>"); + let secondObj = JSON.parse(secondObjStr); + console.log(secondObj); + console.table(secondObj); + } + </script> +</body> + +</html> diff --git a/LectureCodeExamples/Week4/JSObjectsFetchCode/Objects.html b/LectureCodeExamples/Week4/JSObjectsFetchCode/Objects.html new file mode 100755 index 0000000000000000000000000000000000000000..aedcde63b0add62c0033c106a6fbadb387b19aa7 --- /dev/null +++ b/LectureCodeExamples/Week4/JSObjectsFetchCode/Objects.html @@ -0,0 +1,91 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> + <meta charset="utf-8"> + <title>JS Objects Example</title> +</head> + +<body> + <script> + main(); + + function main() { + /* Alternatives for creating an empty object */ + let emptyObject1 = new Object(); + let emptyObject2 = new Object(undefined); + let emptyObject3 = new Object(null); + let emptyObject4 = {}; + + /* Boolean Object alternative */ + let booleanObject1 = new Object(true); + let booleanObject2 = new Boolean(true); + + /* Number Object alternative */ + let numObject1 = new Object(3); + let numObject2 = new Number(3); + + /* String Object alternative */ + let strObject1 = new Object("Hello world"); + let strObject2 = new String("Hello world"); + + /* Using Object constructor for person object */ + let person1 = new Object(); + /* Adding properties */ + /* Alternative to next assignment -> person1.name = "John"; */ + person1["name"] = "John"; + person1.age = 45; + person1.school = umcpSchool; + /* Printing person */ + printPerson(person1); + + /* Using object initializer/literal notation */ + let person2 = { + name: "Mary", /* We could have used "name":"Mary" */ + age: 30, /* We could have used "age": 30 */ + school: umcpSchool, /* Assigning a method */ + bestFriend: person1 /* Assigning an object */ + }; + /* Printing person */ + printPerson(person2); + + let exam = { + semester: "fall", + "difficulty-level": 10, /* Needs " " as key is not valid */ + 3: "midterm3", + "": "empty string" + }; + exam[person1] = "person1"; + + /* Printing to console */ + document.writeln("<br>***** Check console for output *****<br>"); + console.log("\n\n ***** Printing exam object *****\n\n"); + console.log(exam); + console.log("\n\n ***** Printing exam object using table *****\n\n"); + console.table(exam); /* Using console.table */ + + console.log(" ***** Creating object copy *****\n"); + let exam2 = Object.create(exam); + exam2['3'] = 'final'; + console.table(exam2); + } + + function printPerson(personParam) { + document.writeln("Name: " + personParam.name + ", "); + document.writeln("Age: " + personParam.age + ", "); + if (personParam.bestFriend != undefined) { + document.writeln( + "Best Friend: " + personParam.bestFriend.name + ", " + ); + } + personParam.school(); + } + + function umcpSchool() { + document.writeln("University of MD College Park" + "<br>"); + } + + </script> +</body> + +</html> diff --git a/LectureSlides/Week4/JSObjectsFetch.pdf b/LectureSlides/Week4/JSObjectsFetch.pdf new file mode 100644 index 0000000000000000000000000000000000000000..9e0ceb579d01de0fb27d4906ffccc31245d31143 Binary files /dev/null and b/LectureSlides/Week4/JSObjectsFetch.pdf differ