-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
77 lines (68 loc) · 2.68 KB
/
Copy pathscript.js
File metadata and controls
77 lines (68 loc) · 2.68 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
const apiKey = "55e1551653599c4936a7845d7111c387"; // replace with your OpenWeatherMap API key
const searchBtn = document.getElementById("searchBtn");
const weatherResult = document.getElementById("weatherResult");
const historyBox = document.getElementById("history");
const BACKEND_URL = "https://weatherdashboard-1-07nj.onrender.com/"; // <-- your Render app URL
searchBtn.addEventListener("click", () => {
const city = document.getElementById("city").value.trim();
if (!city) return alert("Please enter a city name");
fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`)
.then(res => res.json())
.then(data => {
if (data.cod === 200) {
const icon = getWeatherIcon(data.weather[0].main);
weatherResult.innerHTML = `
<h2>${data.name}, ${data.sys.country}</h2>
<p>${icon} <strong>${data.weather[0].description.toUpperCase()}</strong></p>
<p>🌡️ Temperature: ${data.main.temp}°C</p>
<p>💧 Humidity: ${data.main.humidity}%</p>
<p>🌬️ Wind Speed: ${data.wind.speed} m/s</p>
`;
// Save search to deployed backend
fetch(`${BACKEND_URL}/history`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ city: data.name })
})
.then(() => loadHistory())
.catch(err => console.error("Error saving history:", err));
} else {
weatherResult.innerHTML = `<p>⚠️ City not found! Please try again.</p>`;
}
})
.catch(err => {
console.error("Error fetching weather data:", err);
weatherResult.innerHTML = `<p>⚠️ Error fetching weather data</p>`;
});
});
// Function to get weather icon
function getWeatherIcon(condition) {
switch(condition.toLowerCase()) {
case "clear": return "☀️";
case "clouds": return "☁️";
case "rain": return "🌧️";
case "drizzle": return "🌦️";
case "thunderstorm": return "⛈️";
case "snow": return "❄️";
case "mist":
case "haze":
case "fog": return "🌫️";
default: return "🌍";
}
}
// Load last 5 searches from deployed backend
function loadHistory() {
fetch(`${BACKEND_URL}/history`) // GET request
.then(res => res.json())
.then(data => {
historyBox.innerHTML = "<h3>Recent Searches</h3><ul>" +
data.map(item => `<li>📍 ${item.city} (${new Date(item.searched_at).toLocaleString()})</li>`).join("") +
"</ul>";
})
.catch(err => {
console.error("Error loading history:", err);
historyBox.innerHTML = "<p>⚠️ Cannot load history</p>";
});
}
// Load history on page load
loadHistory();