Skip to content

Commit

Permalink
Lesson 14 - Code
Browse files Browse the repository at this point in the history
  • Loading branch information
tomer79sagi committed Dec 18, 2023
1 parent ed4b0a8 commit f8b09c2
Show file tree
Hide file tree
Showing 10 changed files with 363 additions and 0 deletions.
25 changes: 25 additions & 0 deletions 14 - 17.12.23/13 - homework/2/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>Promise + async/await</h2>

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

<hr/>

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

</table>
</div>
</body>
</html>
24 changes: 24 additions & 0 deletions 14 - 17.12.23/13 - homework/2/script.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
let div = document.getElementById("div");


function randomNumber(num) {
let myPromise = new Promise((resolve, reject) => {

setTimeout(() => {
let randomNumber = Math.floor(Math.random() * num);
console.log(`random number from settimeout ${randomNumber}`);
resolve(randomNumber)
}, 1000);

});

return myPromise;
}


async function main() {
let num = prompt(`enter number`)
div.innerHTML = await randomNumber(num)
}

main()
27 changes: 27 additions & 0 deletions 14 - 17.12.23/13 - homework/4.1/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<!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>Promise + async/await</h2>

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

<hr/>

<div id="output">

</div>

<div id="comments">

</div>
</body>
</html>
35 changes: 35 additions & 0 deletions 14 - 17.12.23/13 - homework/4.1/script.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
function getFromServer(apiEndpoint) {
let myPromise = new Promise((resolve, reject) => {

const xhr = new XMLHttpRequest();
xhr.open('GET', `https://jsonplaceholder.typicode.com/${apiEndpoint}`);

xhr.onload = () => {
if (xhr.status === 200) {
resolve(JSON.parse(xhr.responseText)); // Resolve with the response data.
} else {
reject('Error: Unable to fetch data'); // Reject with an error message.
}
};

xhr.onerror = () => {
reject('Network error'); // Reject if there's a network error.
};

xhr.send();

});

return myPromise;
}


async function main() {
let div = document.getElementById("output");
div.innerHTML = await getFromServer('users');

let commentsDiv = document.getElementById('comments');
commentsDiv.innerHTML = await getFromServer('comments');
}

main();
27 changes: 27 additions & 0 deletions 14 - 17.12.23/13 - homework/4/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<!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>Promise + async/await</h2>

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

<hr/>

<div id="output">

</div>

<div id="comments">

</div>
</body>
</html>
60 changes: 60 additions & 0 deletions 14 - 17.12.23/13 - homework/4/script.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
function getUsers() {
let myPromise = new Promise((resolve, reject) => {

const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://jsonplaceholder.typicode.com/users', true);

xhr.onload = () => {
if (xhr.status === 200) {
resolve(JSON.parse(xhr.responseText)); // Resolve with the response data.
} else {
reject('Error: Unable to fetch data'); // Reject with an error message.
}
};

xhr.onerror = () => {
reject('Network error'); // Reject if there's a network error.
};

xhr.send();

});

return myPromise;
}

function getComments() {
let myPromise = new Promise((resolve, reject) => {

const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://jsonplaceholder.typicode.com/comments', true);

xhr.onload = () => {
if (xhr.status === 200) {
resolve(JSON.parse(xhr.responseText)); // Resolve with the response data.
} else {
reject('Error: Unable to fetch data'); // Reject with an error message.
}
};

xhr.onerror = () => {
reject('Network error'); // Reject if there's a network error.
};

xhr.send();

});

return myPromise;
}


async function main() {
let div = document.getElementById("output");
div.innerHTML = await getUsers()

let commentsDiv = document.getElementById('comments');
commentsDiv.innerHTML = await getComments();
}

main()
25 changes: 25 additions & 0 deletions 14 - 17.12.23/fetch_get/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>17.12.23</h1>
<h2>Fetch</h2>

<div id="buttons">
<button id="btnLoad">Start</button>
</div>

<hr/>

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

</table>
</div>
</body>
</html>
48 changes: 48 additions & 0 deletions 14 - 17.12.23/fetch_get/script.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// -- MODEL --
// 1. Makes call to server
// 2. Returns a Promise object
async function getData() {

// 1. 1st option, using async/await
let response = await fetch('https://jsonplaceholder.typicode.com/posts');
if (response.ok) { // if HTTP status is within the range of 200 and 299
return response.json(); // Similar to JSON.parse();
}

// 2. 2nd option, similar to Promise with .then() and .catch()
// fetch('https://jsonplaceholder.typicode.com/posts')
// .then(data => {
// // ... Scope
// })
// .catch();
}

// -- VIEW --
// Responsible for updating the UI with data
// אחראי על עדכון הממשק משתמש באמצעות דאטה שהוא מקבל כקלט לפונקציה
function updateUI(data) {
// משתנה שישמור את התוכן של הטבלה שיתעדכן בכל איטרציה של הלולאה
let htmlContent = '';

// לולאה שעוברת על כל האיברים מהמערך שהתקבל מהתשובה של השרת
for (let post of data) {
htmlContent += `
<tr>
<td>${post.userId}</td>
<td>${post.id}</td>
<td>${post.title}</td>
<td>${post.body}</td>
</tr>
`;
}

document.getElementById('output').innerHTML = `<table>${htmlContent}</table>`;
}

// -- CONTROL --
async function main() {
const data = await getData();
updateUI(data);
}

main();
25 changes: 25 additions & 0 deletions 14 - 17.12.23/fetch_post/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>17.12.23</h1>
<h2>Fetch</h2>

<div id="buttons">
<button id="btnLoad">Start</button>
</div>

<hr/>

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

</table>
</div>
</body>
</html>
67 changes: 67 additions & 0 deletions 14 - 17.12.23/fetch_post/script.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
// -- MODEL --
// 1. Makes call to server
// 2. Returns a Promise object
async function getData() {

// 1. 1st option, using async/await
let response = await fetch('https://jsonplaceholder.typicode.com/posts');
if (response.ok) { // if HTTP status is within the range of 200 and 299
return response.json(); // Similar to JSON.parse();
}
}

async function postData() {
const myPost = {
title: 'foo',
body: 'bar',
userId: 1,
};

// 1. 1st option, using async/await
let response = await fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
body: JSON.stringify(myPost),
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
});

if (response.ok) { // if HTTP status is within the range of 200 and 299
return response.json(); // Similar to JSON.parse();
}
}

// -- VIEW --
// Responsible for updating the UI with data
// אחראי על עדכון הממשק משתמש באמצעות דאטה שהוא מקבל כקלט לפונקציה
function updateUI(data) {
// משתנה שישמור את התוכן של הטבלה שיתעדכן בכל איטרציה של הלולאה
let htmlContent = '';

// לולאה שעוברת על כל האיברים מהמערך שהתקבל מהתשובה של השרת
for (let post of data) {
htmlContent += `
<tr>
<td>${post.userId}</td>
<td>${post.id}</td>
<td>${post.title}</td>
<td>${post.body}</td>
</tr>
`;
}

document.getElementById('output').innerHTML = `<table>${htmlContent}</table>`;
}

// -- CONTROL --
async function main() {
// 1. Get list of posts from server - GET
let data = await getData();
updateUI(data);

// 2. Create new post on server - POST
data = await postData();
alert(data);
}

main();

0 comments on commit f8b09c2

Please sign in to comment.