-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
85 lines (75 loc) · 2.84 KB
/
script.js
File metadata and controls
85 lines (75 loc) · 2.84 KB
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
// ✅ Update this to your Render backend URL
const API_BASE = "https://share-memories-backend-mlkf.onrender.com";
// Form submission to add a new memory
const form = document.getElementById("memoryForm");
form.addEventListener("submit", async (e) => {
e.preventDefault();
const name = document.getElementById("name").value.trim();
const likes = document.getElementById("likes").value.trim();
const regret = document.getElementById("regret").value.trim();
const memories = document.getElementById("memories").value.trim();
// Check if all fields are filled
if (name && likes && regret && memories) {
try {
// Send a POST request to add a new memory
const response = await fetch(`${API_BASE}/api/memories`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
name,
likes,
regret,
memories,
}),
});
const data = await response.json();
if (response.status === 201) {
alert("Memory submitted successfully!");
form.reset(); // Reset form fields after successful submission
} else {
alert("Error: " + (data.error || "An unexpected error occurred."));
}
} catch (err) {
console.error("Error adding memory:", err);
alert("An error occurred while submitting the memory. Please try again.");
}
} else {
alert("Please fill out all fields.");
}
});
// Load and display all memories on the "View Memories" button click
document.getElementById("viewBtn").addEventListener("click", async () => {
const messagesContainer = document.getElementById("messages");
messagesContainer.innerHTML = "<p>Loading memories...</p>"; // Show loading message
try {
// Fetch memories from the backend
const response = await fetch(`${API_BASE}/api/memories`);
// Handle non-200 responses
if (!response.ok) {
throw new Error("Failed to fetch memories.");
}
const memories = await response.json();
if (memories.length === 0) {
messagesContainer.innerHTML = "<p>No memories found.</p>";
} else {
messagesContainer.innerHTML = ""; // Clear loading message
memories.forEach((data) => {
// Append each memory to the container
messagesContainer.innerHTML += `
<div class="memory-card">
<h3>${data.name}</h3>
<p><strong>Likes:</strong> ${data.likes}</p>
<p><strong>Regret:</strong> ${data.regret}</p>
<p><strong>Memories:</strong> ${data.memories}</p>
<p><em>Submitted on: ${new Date(data.timestamp).toLocaleString()}</em></p>
</div>
`;
});
}
} catch (err) {
console.error("Error fetching memories:", err);
messagesContainer.innerHTML = "<p>Failed to load memories. Please try again later.</p>";
}
});