Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 06. Phonebook
- // HTTP and REST - Exercises
- // https://judge.softuni.org/Contests/Compete/Index/3798#5
- function attachEvents() {
- const baseUrl = 'http://localhost:3030/jsonstore/phonebook'
- const phonebook = document.getElementById('phonebook');
- const inputId = document.getElementById('person');
- const inputPhone = document.getElementById('phone');
- const loadBtn = document.getElementById('btnLoad');
- const createBtn = document.getElementById('btnCreate');
- loadBtn.addEventListener('click', load);
- createBtn.addEventListener('click', createNewContact);
- load()
- let personIds = {};
- function load() {
- phonebook.innerHTML = "";
- fetch(baseUrl)
- .then(response => response.json())
- .then(data => {
- for (let obj in data) {
- personIds[data[obj]['person']] = data[obj]['_id'];
- let newLi = document.createElement('li');
- newLi.textContent = `${data[obj]['person']}: ${data[obj]['phone']}`
- let deleteBtn = document.createElement('button');
- deleteBtn.textContent = 'Delete';
- newLi.appendChild(deleteBtn);
- phonebook.appendChild(newLi);
- deleteBtn.addEventListener('click', deleteContact);
- }
- })
- }
- function createNewContact() {
- let person = inputId.value;
- let phone = inputPhone.value;
- fetch(baseUrl, {
- method: "POST",
- headers: {
- 'content-type': 'application/json'
- },
- body: JSON.stringify({
- 'person': person,
- 'phone': phone
- })
- })
- inputId.value = '';
- inputPhone.value = '';
- document.location.reload();
- }
- function deleteContact(e) {
- let contactInfo = e.target.parentNode.textContent;
- let person = contactInfo.split(':')[0];
- let id = personIds[person];
- let deleteUrl = `${baseUrl}/${id}`;
- fetch(deleteUrl, {
- method: "DELETE",
- })
- e.target.parentNode.textContent = 'Contact Deleted';
- }
- }
- attachEvents();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement