-
Notifications
You must be signed in to change notification settings - Fork 0
/
addUser.js
86 lines (82 loc) · 3.25 KB
/
addUser.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// получаем нашу форму
const form = document.forms["addUser"];
// создаём функцию "создать пост"
function createPost(body, callback) {
return new Promise((resolve, reject) => {
const request = new XMLHttpRequest();
request.open("POST", "https://jsonplaceholder.typicode.com/posts");
request.addEventListener("load", () => {
const response = JSON.parse(request.responseText);
// console.log(response);
if (request.status >= 400) {
reject(request.response);
} else {
resolve(request.response);
}
callback(response);
});
request.setRequestHeader("Content-type", "application/json; charset=UTF-8");
request.send(JSON.stringify(body));
});
}
// шаблон для поста в котором он будет строится
function newPostTemplate(post) {
const card = document.createElement("div");
card.classList.add("card");
const cardBody = document.createElement("div");
cardBody.classList.add("card-body");
const userBtn = document.createElement("button");
userBtn.setAttribute("type", "button");
userBtn.classList.add("btn", "btn-info", "btn-lg");
userBtn.setAttribute("data-bs-toggle", "popover");
userBtn.setAttribute("data-bs-html", "true");
userBtn.setAttribute(
"data-bs-title",
"Additional information about the user: "
);
userBtn.setAttribute(
"data-bs-content",
`Username: ${post.username}<br/>Email: ${post.email}<br/>Phone: ${post.phone}<br/> Website: ${post.website}`
);
const title = document.createElement("h5");
title.classList.add("card-title");
title.textContent = post.name;
userBtn.appendChild(title);
cardBody.appendChild(userBtn);
card.appendChild(cardBody);
return card;
}
// кнопка добавления поста в html
addUsersBtn.addEventListener("click", postNewUser);
// Запостить юзера
function postNewUser(e) {
e.preventDefault();
// всю логику всовываем в if для проверки валидности формы. Почему? Потому-что по стандарту валидацию мы отключили в строчке сверху
if (form.checkValidity()) {
// записать value из инпутов формы
const name = form.elements.namedItem("name").value;
const username = form.elements.namedItem("username").value;
const email = form.elements.namedItem("email").value;
const phone = form.elements.namedItem("phone").value;
const website = form.elements.namedItem("website").value;
// создать объект нашего юзера из данных записанных в переменные из инпутов формы
const newPost = {
name: name,
username: username,
email: email,
phone: phone,
website: website,
user_id: `id_${Math.random() * Math.random()}`,
};
// создать пост
createPost(newPost, (response) => {
const card = newPostTemplate(response);
container.insertAdjacentElement("afterbegin", card);
form.reset();
initPopovers();
});
// а если не валидно дать ошибку и не выполнить логику
} else {
form.classList.add("was-validated");
}
}