Advertisement
GeorgiLukanov87

05. Messenger

Feb 28th, 2023
876
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function attachEvents() {
  2.     const url = 'http://localhost:3030/jsonstore/messenger'
  3.     const textArea = document.getElementById('messages');
  4.     const sendBtn = document.getElementById('submit');
  5.     const refreshBtn = document.getElementById('refresh');
  6.  
  7.     const senderName = document.querySelector('#controls > div:nth-child(1) > input[type=text]')
  8.     const senderMsg = document.querySelector('#controls > div:nth-child(2) > input[type=text]')
  9.  
  10.     senderName.value = 'Spami'
  11.     senderMsg.value = 'Hello, George nice to see you! :)))'
  12.  
  13.     sendBtn.addEventListener('click', onSend);
  14.     refreshBtn.addEventListener('click', onRefresh);
  15.  
  16.     loadMessages()
  17.    
  18.     function loadMessages() {
  19.         fetch(url).then(response => response.json()).then(result => {
  20.             for (let i in result) {
  21.                 console.log(result[i])
  22.                 textArea.textContent += `${result[i].author}: ${result[i].content}\n`
  23.             }
  24.         })
  25.     }
  26.  
  27.  
  28.     function onSend() {
  29.         let authorName = senderName.value
  30.         let msgText = senderMsg.value;
  31.  
  32.         fetch(url, {
  33.             method: "POST",
  34.             headers: {
  35.                 'content-type': 'application/json'
  36.             },
  37.             body: JSON.stringify({
  38.                 author: authorName,
  39.                 content: msgText
  40.             })
  41.         })
  42.  
  43.     }
  44.  
  45.     function onRefresh() {
  46.         textArea.textContent = ""
  47.         fetch(url)
  48.             .then(response => response.json())
  49.             .then(result => {
  50.                 for (let i in result) {
  51.                     console.log(result[i])
  52.                     textArea.textContent += `${result[i].author}: ${result[i].content}\n`
  53.                 }
  54.             })
  55.         senderName.value = ""
  56.         senderMsg.value = ""
  57.     }
  58.  
  59. }
  60.  
  61. attachEvents();
  62.  
  63.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement