Advertisement
GeorgiLukanov87

06. Phonebook

Mar 23rd, 2023 (edited)
711
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // 06. Phonebook
  2. // HTTP and REST - Exercises
  3. // https://judge.softuni.org/Contests/Compete/Index/3798#5
  4.  
  5. function attachEvents() {
  6.     const baseUrl = 'http://localhost:3030/jsonstore/phonebook'
  7.  
  8.     const phonebook = document.getElementById('phonebook');
  9.     const inputId = document.getElementById('person');
  10.     const inputPhone = document.getElementById('phone');
  11.  
  12.     const loadBtn = document.getElementById('btnLoad');
  13.     const createBtn = document.getElementById('btnCreate');
  14.  
  15.     loadBtn.addEventListener('click', load);
  16.     createBtn.addEventListener('click', createNewContact);
  17.  
  18.     load()
  19.     let personIds = {};
  20.  
  21.     function load() {
  22.         phonebook.innerHTML = "";
  23.         fetch(baseUrl)
  24.             .then(response => response.json())
  25.             .then(data => {
  26.                 for (let obj in data) {
  27.                     personIds[data[obj]['person']] = data[obj]['_id'];
  28.                     let newLi = document.createElement('li');
  29.                     newLi.textContent = `${data[obj]['person']}: ${data[obj]['phone']}`
  30.                     let deleteBtn = document.createElement('button');
  31.                     deleteBtn.textContent = 'Delete';
  32.                     newLi.appendChild(deleteBtn);
  33.                     phonebook.appendChild(newLi);
  34.  
  35.                     deleteBtn.addEventListener('click', deleteContact);
  36.                 }
  37.             })
  38.     }
  39.  
  40.     function createNewContact() {
  41.         let person = inputId.value;
  42.         let phone = inputPhone.value;
  43.  
  44.         fetch(baseUrl, {
  45.             method: "POST",
  46.             headers: {
  47.                 'content-type': 'application/json'
  48.             },
  49.             body: JSON.stringify({
  50.                 'person': person,
  51.                 'phone': phone
  52.             })
  53.         })
  54.         inputId.value = '';
  55.         inputPhone.value = '';
  56.         document.location.reload();
  57.     }
  58.  
  59.     function deleteContact(e) {
  60.         let contactInfo = e.target.parentNode.textContent;
  61.         let person = contactInfo.split(':')[0];
  62.         let id = personIds[person];
  63.         let deleteUrl = `${baseUrl}/${id}`;
  64.         fetch(deleteUrl, {
  65.             method: "DELETE",
  66.         })
  67.         e.target.parentNode.textContent = 'Contact Deleted';
  68.     }
  69. }
  70.  
  71. attachEvents();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement