Concepts Used: $.ajax()
, API call
Features:
- Get weather by city using OpenWeatherMap API (free key required).
<!DOCTYPE html>
<html>
<head>
<title>Weather App</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h2>Weather App</h2>
<input type="text" id="city" placeholder="Enter City">
<button id="getWeather">Get Weather</button>
<p id="weather"></p>
<script>
$(document).ready(function(){
$("#getWeather").click(function(){
let city = $("#city").val();
let apiKey = "YOUR_API_KEY"; // <-- Replace with your OpenWeatherMap key
$.ajax({
url: https://api.openweathermap.org/data/2.5/weather?q=${city}&amp;appid=${apiKey}&amp;units=metric
,
method: "GET",
success: function(data){
$("#weather").text(Temperature: ${data.main.temp}°C, ${data.weather&#91;0].description}
);
},
error: function(){
$("#weather").text("City not found!");
}
});
});
});
</script>
</body>
</html>
Explanation:
- Uses
$.ajax()
to fetch weather JSON data. - Displays temperature & description dynamically.
Leave a Reply