Advertisement
svetlyoek

Untitled

Jul 6th, 2020
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.67 KB | None | 0 0
  1. function attachEvents() {
  2.  
  3. const sendBtn = document.getElementById('submit');
  4. const refreshBtn = document.getElementById('refresh');
  5. const messages = document.getElementById('messages');
  6. const author = document.getElementById('author');
  7. const message = document.getElementById('content');
  8.  
  9. const url = `http://localhost:3000/messenger`;
  10.  
  11. sendBtn.addEventListener('click', function (e) {
  12.  
  13. if (author.value !== '' && message.value !== '') {
  14.  
  15. fetch(url, {
  16. method: 'POST',
  17. body: JSON.stringify({
  18. author: author.value,
  19. content: message.value
  20. })
  21. })
  22. .then((response) => {
  23.  
  24. if (!response.ok) {
  25.  
  26. console.error('Something get wrong!');
  27.  
  28. } else {
  29.  
  30. return response.json();
  31. }
  32. })
  33. .then((response) => {
  34.  
  35. author.value = '';
  36. message.value = '';
  37. });
  38. }
  39. });
  40.  
  41. refreshBtn.addEventListener('click', function (e) {
  42.  
  43. fetch(url)
  44. .then((response) => {
  45.  
  46. if (!response.ok) {
  47.  
  48. console.error('Something get wrong!');
  49.  
  50. } else {
  51.  
  52. return response.json();
  53. }
  54. })
  55. .then((data) => {
  56.  
  57. messages.textContent = '';
  58.  
  59. for (let message of Object.keys(data)) {
  60.  
  61. messages.textContent += `${data[message].author}: ${data[message].content}\n`;
  62. }
  63. });
  64. });
  65. }
  66.  
  67. attachEvents();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement