Skip to content

Commit ed9a641

Browse files
committed
add demos for ajax
1 parent 862d363 commit ed9a641

1 file changed

Lines changed: 69 additions & 1 deletion

File tree

public/scripts/main.js

Lines changed: 69 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,69 @@
1-
// Write chatr code here!
1+
// sends request and loads it into the page
2+
const loadMessages = () => {
3+
fetch('/messages') // sends a GET request to localhost:3434/messages
4+
.then(res => {
5+
// fetch will always resolve to a response object
6+
// we need to call res.json() to turn the contents/body
7+
// of the response into json
8+
return res.json(); // this returns a promise which we can
9+
// chain .then() on
10+
}).then(messages => {
11+
console.log(messages);
12+
const messagesContainer = document.querySelector('#messages'); // grab the container for the messages from the DOM
13+
let messagesHTML = ''; // hold the list of messages html
14+
messages.forEach(message => { // for every message create an li that holds info about the mesage
15+
messagesHTML += `
16+
<li>
17+
${message.body}
18+
</br>
19+
${message.username}
20+
<i data-id=${message.id} class="delete-link">x</i>
21+
</li>
22+
`
23+
});
24+
messagesContainer.innerHTML = messagesHTML;
25+
});
26+
}
27+
28+
const createMessage = (message) => {
29+
fetch("/messages", {
30+
method: 'POST',
31+
body: message
32+
}).then(() => {
33+
document.querySelector('#new-message').reset();
34+
loadMessages();
35+
})
36+
}
37+
38+
const deleteMessage = (id) => {
39+
fetch(`/messages/${id}`, {
40+
method: "DELETE"
41+
}).then(() => {
42+
loadMessages();
43+
})
44+
}
45+
46+
47+
const REFRESH_INTERVAL = 3000;
48+
document.addEventListener('DOMContentLoaded', () => {
49+
loadMessages();
50+
setInterval(loadMessages, REFRESH_INTERVAL);
51+
52+
const newMessageForm = document.querySelector('#new-message');
53+
newMessageForm.addEventListener('submit', event => {
54+
event.preventDefault();
55+
const form = event.currentTarget;
56+
const fd = new FormData(form);
57+
fd.set('username', 'batman');
58+
createMessage(fd);
59+
})
60+
61+
const messageContainer = document.querySelector('#messages');
62+
messageContainer.addEventListener('click', event => {
63+
if (event.target.matches("i.delete-link")) {
64+
const id = event.target.dataset.id;
65+
deleteMessage(id);
66+
}
67+
})
68+
})
69+

0 commit comments

Comments
 (0)