Skip to content

Commit

Permalink
Lesson 13 code committed
Browse files Browse the repository at this point in the history
  • Loading branch information
tomer79sagi committed Dec 13, 2023
1 parent bf60a0b commit ed4b0a8
Show file tree
Hide file tree
Showing 15 changed files with 542 additions and 1 deletion.
2 changes: 1 addition & 1 deletion 11 - 03.12.23/xmlhttprequest_post/script.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ function getSingleUser() {

xhr.onload = () => {
// JSON.parse() --> Convert JSON text to Javascript object
const userObj = JSON.parse(xhr.responseText);
const userObj = JSON.parse(xhr.responseText);S

// Iterate / loop over all attributes in the 'responseObj'
for (let prop in userObj) {
Expand Down
22 changes: 22 additions & 0 deletions 13 - 13.12.23/12_homework/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>19.11.23</title>
<script defer src="./script.js"></script>
</head>
<body>
<h1>13.12.23</h1>
<h2>Promise - Homework</h2>

<div id="buttons">
<button id="btnLoad">Request flag name</button>
</div>

<hr/>

<div id="output">
</div>
</body>
</html>
60 changes: 60 additions & 0 deletions 13 - 13.12.23/12_homework/script.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
function getData(countryName) {
const myPromise = new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();

xhr.onload = () => {
// Check if the response is valid and OK
if (xhr.status === 200) {
resolve(xhr.responseText);
} else {
reject(xhr.statusText);
}
};

xhr.open('GET', `https://restcountries.com/v3.1/name/${countryName}`);
xhr.send();
});

return myPromise;
}

function printData() {
const cName = prompt('Please enter a country name');
const p = getData(cName); // 'p' --> object of class Promise

p.then((data) => {
console.log(JSON.parse(data));
});
}

function setImages() {
const flagSources = [];
let inputName;
let counter = 5;

// 1. Get country names into an array
for (counter=0 ; counter<5 ; counter++) {
inputName = prompt(`Please enter country name ${i}`);
flagSources.push(inputName);
}

// 2. Make API calls to get image sources and construct URLs
let imgHTML = '';
for (counter=0 ; counter<5 ; counter++) {
imgHTML += `
<div>
<img src="${flagsSources[counter]}"/>
</div>
`;
}

// 3. Append the new img src to the
}

document.getElementById('btnLoad').addEventListener('click', printData);

// const myPromise = getData('Israel');
// myPromise
// .then((data) => console.log(data))
// .catch(error => alert(error));

22 changes: 22 additions & 0 deletions 13 - 13.12.23/class_exercise_1/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>19.11.23</title>
<script defer src="./script.js"></script>
</head>
<body>
<h1>13.12.23</h1>
<h2>Promise - Homework</h2>

<div id="buttons">
<button id="btnLoad">Request flag name</button>
</div>

<hr/>

<div id="output">
</div>
</body>
</html>
25 changes: 25 additions & 0 deletions 13 - 13.12.23/class_exercise_1/script.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
function randomNumber() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const randomNumber = Math.random();
resolve(randomNumber);
}, 3000);
});
}

async function main() {
// -- Option 1 without Promise or any asynchornous code
// Code runs from start to finish and DOESN'T WAIT for the resolve() to execute
// const randomNum = randomNumber(); // This is a asynchornous function and we want to wait here until the Promise is resolved
// document.getElementById('output').innerHTML = randomNum;

// -- Option 2 with Promise + .then() --> works but messy
// const p = randomNumber();
// p.then(data => document.getElementById('output').innerHTML = data); // This is a asynchornous function and we want to wait here until the Promise is resolved

// -- Option 3 with Promise + async/await --> clean code, clear, perfect!
const randomNum = await randomNumber(); // This is a asynchornous function and we want to wait here until the Promise is resolved
document.getElementById('output').innerHTML = randomNum;
}

main();
22 changes: 22 additions & 0 deletions 13 - 13.12.23/class_exercise_callback/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>19.11.23</title>
<script defer src="./script.js"></script>
</head>
<body>
<h1>13.12.23</h1>
<h2>Promise - Homework</h2>

<div id="buttons">
<button id="btnLoad">Request flag name</button>
</div>

<hr/>

<div id="output">
</div>
</body>
</html>
53 changes: 53 additions & 0 deletions 13 - 13.12.23/class_exercise_callback/script.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@

// Prints a name somewhere
// 'somewhere' = callback function
// -------
// 'name' = name to print
// 'whereFunction' = a callback function, i.e. a pointer to a function code in memory
function displayName(name, whereFunction) {
whereFunction(name);
}


// display functions
function displayToAlert(name) {
alert(name);
}

function displayToConsole(name) {
console.log(name);
}

function displayToHTML(name) {
document.getElementById('output').innerHTML = name;
}

function displayToFile(name) {
//...
}

function clicked() {
alert('clicked');
}

// Old school
displayToAlert('Tomer');
displayToConsole('Tomer');
displayToHTML('Tomer');

// Modern and flexible, using callback
displayName('Tomer', displayToAlert);
displayName('Tomer', displayToConsole);
displayName('Tomer', displayToHTML);
displayName('Tomer', displayToFile);

// EVENTS use callback functions
// Eventlistener for click events
document.getElementById('output').addEventListener('click', clicked);

// Using XMLHttpRequest
const xhr = new XMLHttpRequest();
xhr.onload = clicked;

// Using asynchronous code - setTimeout
setTimeout(clicked, 3000);
25 changes: 25 additions & 0 deletions 13 - 13.12.23/xmlhttprequest_0.5 - callback/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>19.11.23</title>
<script defer src="./script.js"></script>
</head>
<body>
<h1>10.12.23</h1>
<h2>XMLHttpRequest - Homework</h2>

<div id="buttons">
<button id="btnLoad">Load content</button>
</div>

<hr/>

<div id="output">
<table id='myTable'>

</table>
</div>
</body>
</html>
48 changes: 48 additions & 0 deletions 13 - 13.12.23/xmlhttprequest_0.5 - callback/script.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// -- MODEL --
// Function that retrieves data from server
const getUsersFromServer = (callbackFunc) => {
const xhr = new XMLHttpRequest(); // new instance of class 'XMLHttpReqeust'

// When a 'completed' request was called and a 'completed' response was sent back
// Here we will handle both successful server actions and unsuccessful server actions
xhr.onload = () => {
// JSON.parse() --> Convert JSON text to Javascript object
usersObj = JSON.parse(xhr.responseText);
callbackFunc(usersObj);
}

xhr.open('GET', 'https://jsonplaceholder.typicode.com/users'); // == READ, Type: 'xhr' in 'Netowrk' tab in 'F12 - Developer Tools'
xhr.send();
}

// -- VIEW --
// פונקציה שמקבלת מערך של אובייקטים של משתמשים ומייצרת טבלה להציג אותם
// Function that recieves array of JS objects and creates a table with the information
const createTableFromUsers = (arrUsers) => {
let usersHTML = '';

// Create all <TR>s for all users
for (let user of usersObj) {
usersHTML += `
<tr>
<td>${user.id}</td>
<td>${user.name}</td>
<td>${user.email}</td>
<td>${user.phone}</td>
</tr>
`;
}

// 1. Add titles to the userHTML
// 2. Add to DOM
document.getElementById('myTable').innerHTML = usersHTML;
}

// -- CONTROLLER -- מתכלל הפעולות בתוכנה
const displayUsers = () => {
// 1. Call server
getUsersFromServer(createTableFromUsers);
}

// נחבר את אירוע הלחיצה לפונקציית קבלת המידע מהשרת
document.getElementById('btnLoad').addEventListener('click', displayUsers);
25 changes: 25 additions & 0 deletions 13 - 13.12.23/xmlhttprequest_0/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>19.11.23</title>
<script defer src="./script.js"></script>
</head>
<body>
<h1>10.12.23</h1>
<h2>XMLHttpRequest - Homework</h2>

<div id="buttons">
<button id="btnLoad">Load content</button>
</div>

<hr/>

<div id="output">
<table id='myTable'>

</table>
</div>
</body>
</html>
51 changes: 51 additions & 0 deletions 13 - 13.12.23/xmlhttprequest_0/script.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// -- MODEL --
// Function that retrieves data from server
const getUsersFromServer = () => {
const xhr = new XMLHttpRequest(); // new instance of class 'XMLHttpReqeust'

// When a 'completed' request was called and a 'completed' response was sent back
// Here we will handle both successful server actions and unsuccessful server actions
xhr.onload = () => {
// JSON.parse() --> Convert JSON text to Javascript object
usersObj = JSON.parse(xhr.responseText);
let usersHTML = '';

// Create all <TR>s for all users
for (let user of usersObj) {
usersHTML += `
<tr>
<td>${user.id}</td>
<td>${user.name}</td>
<td>${user.email}</td>
<td>${user.phone}</td>
</tr>
`;
}

// 1. Add titles to the userHTML
// 2. Add to DOM
document.getElementById('myTable').innerHTML = usersHTML;
}

xhr.open('GET', 'https://jsonplaceholder.typicode.com/users'); // == READ, Type: 'xhr' in 'Netowrk' tab in 'F12 - Developer Tools'
xhr.send();
}

// -- VIEW --
// פונקציה שמקבלת מערך של אובייקטים של משתמשים ומייצרת טבלה להציג אותם
// Function that recieves array of JS objects and creates a table with the information
const createTableFromUsers = (arrUsers) => {

}

// -- CONTROLLER -- מתכלל הפעולות בתוכנה
const displayUsers = () => {
// 1. Call server
const arrUsers = getUsersFromServer();

// 2. Update UI
createTableFromUsers(arrUsers);
}

// נחבר את אירוע הלחיצה לפונקציית קבלת המידע מהשרת
document.getElementById('btnLoad').addEventListener('click', displayUsers);
Loading

0 comments on commit ed4b0a8

Please sign in to comment.