Fetching Data from OpenWeather API using jQuery
Fetching data from an API is one of the most crucial tasks when developing web applications. OpenWeather API provides real-time weather information that developers can integrate into their websites or applications. In this guide, we will use jQuery to fetch weather data from the OpenWeather API and display it dynamically on a webpage.
This tutorial covers:
- Introduction to OpenWeather API
- API Key Registration
- Setting Up the Project
- Making API Calls with jQuery AJAX
- Handling API Responses
- Displaying Weather Data on the Webpage
- Enhancing User Experience with Additional Features
- Handling Errors and Edge Cases
- Conclusion
1. Introduction to OpenWeather API
The OpenWeather API provides access to weather data, including current weather, forecasts, and historical weather conditions. It is widely used for weather-related applications in web and mobile development.
Key Features:
- Real-time weather data
- Forecast data for multiple days
- Historical weather information
- Geolocation-based weather retrieval
To use OpenWeather API, you need to sign up and get an API key.
2. API Key Registration
Before making API requests, you must register and obtain an API key.
Steps to Get an API Key:
- Go to OpenWeather API
- Sign up or log in.
- Navigate to API Keys in your account.
- Copy the API key (a long alphanumeric string).
3. Setting Up the Project
We will create a simple HTML page and include jQuery to make API requests.
Project File Structure:
/weather-app
├── index.html
├── script.js
├── style.css
Include jQuery in the Project
You can use the CDN version of jQuery or download it locally.
CDN Link (Include in <head>
)
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
4. Making API Calls with jQuery AJAX
To fetch weather data, we will use the jQuery AJAX method.
API Endpoint Format:
https://api.openweathermap.org/data/2.5/weather?q={city_name}&appid={API_KEY}&units=metric
{city_name}
→ City name (e.g., Hyderabad, London){API_KEY}
→ Your unique OpenWeather API keyunits=metric
→ Returns temperature in Celsius (useimperial
for Fahrenheit)
Basic AJAX Call with jQuery
Create a script.js
file and add the following code:
$(document).ready(function () {
$("#getWeatherBtn").click(function () {
let city = $("#cityInput").val();
let apiKey = "YOUR_API_KEY"; // Replace with your actual API key
let apiUrl = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`;
$.ajax({
url: apiUrl,
type: "GET",
dataType: "json",
success: function (data) {
displayWeather(data);
},
error: function (xhr, status, error) {
alert("Error fetching weather data. Please check the city name.");
}
});
});
function displayWeather(data) {
let cityName = data.name;
let temp = data.main.temp;
let weatherDesc = data.weather[0].description;
let icon = data.weather[0].icon;
let iconUrl = `http://openweathermap.org/img/w/${icon}.png`;
$("#weatherResult").html(`
<h2>${cityName}</h2>
<p>Temperature: ${temp}°C</p>
<p>Condition: ${weatherDesc}</p>
<img src="${iconUrl}" alt="Weather Icon">
`);
}
});
5. Handling API Responses
Expected JSON Response
When you request weather data, the API returns a JSON object like this:
{
"coord": { "lon": 78.4744, "lat": 17.3753 },
"weather": [{ "id": 800, "main": "Clear", "description": "clear sky", "icon": "01d" }],
"main": { "temp": 30.15, "pressure": 1012, "humidity": 45 },
"name": "Hyderabad"
}
From this, we extract:
data.name
→ City namedata.main.temp
→ Temperaturedata.weather[0].description
→ Weather descriptiondata.weather[0].icon
→ Icon for weather condition
6. Displaying Weather Data on the Webpage
Modify index.html
to include an input field, button, and results section.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Weather App</title>
<link rel="stylesheet" href="style.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="script.js" defer></script>
</head>
<body>
<div class="container">
<h1>Weather App</h1>
<input type="text" id="cityInput" placeholder="Enter city name">
<button id="getWeatherBtn">Get Weather</button>
<div id="weatherResult"></div>
</div>
</body>
</html>
7. Enhancing User Experience with Additional Features
Adding Loading Indicator
Modify the script to show a loading message:
$("#getWeatherBtn").click(function () {
$("#weatherResult").html("<p>Loading...</p>");
});
Adding Auto-Complete for Cities
You can use an API like Google Places Autocomplete to suggest cities.
8. Handling Errors and Edge Cases
Invalid City Name
If the user enters an invalid city, the API returns an error. Handle it like this:
error: function (xhr) {
if (xhr.status == 404) {
alert("City not found! Please enter a valid city.");
} else {
alert("An error occurred. Please try again later.");
}
}
Handling Empty Inputs
Ensure the user enters a city before making a request:
let city = $("#cityInput").val().trim();
if (city === "") {
alert("Please enter a city name.");
return;
}
In this tutorial, we covered: ✅ Fetching weather data using jQuery AJAX
✅ Parsing API responses and displaying results
✅ Handling errors gracefully
✅ Enhancing UX with features like loading indicators
This approach is simple and effective for integrating real-time weather updates into web applications. You can further improve it by:
- Using localStorage to save user preferences
- Implementing forecast data instead of current weather
- Adding geolocation support to fetch weather automatically
Would you like to explore another API next?