Create a Temperature Widget using JavaScript and PHP (Auto Location + Live Weather API)

If you want to display real-time temperature, humidity, weather description, and day/night status on your website, this tutorial will help you build a fully functional Temperature Widget using JavaScript and PHP.

This widget:
✔ Detects user location automatically via IP
✔ Fetches live weather data using the Open-Meteo API (no API key required)
✔ Displays:

  • Current temperature in Celsius
  • City / Country
  • Weather description (e.g., Partly Cloudy)
  • Humidity
  • Current date & time
  • Day/Night indicator icon

We’ll use:

  • Frontend: HTML + CSS + JavaScript
    • HTML for the widget structure
    • CSS for styling
    • JavaScript to fetch and display weather data dynamically
  • Backend: PHP
    • PHP to handle server-side requests and fetch weather data from the API
  • Weather API: Open-Meteo (Free, No API Key Required)

📁 Project Structure Overview

Let’s start by creating the necessary files for our temperature widget. Below is the directory structure we will be working with:

temperature-widget/
├── index.html
├── script.js
├── weather.php
└── style.css
  1. index.html: This file will contain the HTML structure of the widget and link to the CSS and JavaScript files.
  2. style.css: This file will contain the CSS styles to make the widget visually appealing and responsive.
  3. script.js: This file will contain the JavaScript code to fetch weather data from the PHP backend and update the widget dynamically.
  4. weather.php: This file will handle the server-side logic to fetch weather data from the Open-Meteo API based on the user’s location and return it as JSON.

The widget will fetch weather data from the Open-Meteo API and display it in a user-friendly format. Below are the steps to create this widget:

Step 1: Create the HTML Structure (index.html)

First, we will create the basic HTML structure for our temperature widget. This will include a container for the widget, sections for the header, main content, and footer where we will display the weather information.

<div class="temp-widget">
    <div class="widget-header">
        <span class="location">Loading...</span>
        <span class="day-night">🌞</span>
    </div>
    <div class="widget-main">
        <span class="temperature">--<sup>°C</sup></span>
        <span class="weather">--</span>
    </div>
    <div class="widget-footer">
        <span class="humidity">Humidity: --%</span>
        <span class="datetime">--</span>
    </div>
</div>

Include JavaScript (script.js) to fetch and display weather data:

<script src="script.js"></script>

Step 2: Style the Widget with CSS (style.css)

Next, we will add CSS styles to make our temperature widget visually appealing and responsive. We will use a clean and modern design with a color scheme that complements the weather data being displayed. The CSS will also ensure that the widget looks good on both desktop and mobile devices.

.temp-widget {
    background: #ffffff;
    width: 280px;
    padding: 20px;
    border-radius: 15px;
    box-shadow: 0 8px 20px rgba(0,0,0,0.15);
}

.widget-header {
    display: flex;
    justify-content: space-between;
    font-weight: bold;
}

.widget-main {
    text-align: center;
    margin: 20px 0;
}

.temperature {
    font-size: 40px;
    font-weight: bold;
}

.weather {
    display: block;
    margin-top: 5px;
    color: #555;
}

.widget-footer {
    display: flex;
    justify-content: space-between;
    font-size: 14px;
}

Step 3: Fetch and Display Weather Data with JavaScript (script.js)

Finally, we will write the JavaScript code to fetch weather data from our PHP backend (weather.php) and update the widget dynamically. The JavaScript will make an AJAX request to the PHP script, which will return the weather data in JSON format. We will then parse this data and update the HTML elements in our widget accordingly.

document.addEventListener('DOMContentLoaded', () => {
    fetch('weather.php')
        .then(response => response.json())
        .then(data => {
            document.querySelector('.location').textContent = data.location || 'Unknown';
            document.querySelector('.temperature').innerHTML = `${data.temperature ?? '--'}<sup>°C</sup>`;
            document.querySelector('.weather').textContent = data.weather || '--';
            document.querySelector('.humidity').textContent = `Humidity: ${data.humidity ?? '--'}%`;
            document.querySelector('.datetime').textContent = data.datetime || '--';
            document.querySelector('.day-night').textContent = data.is_day ? '🌞' : '🌜';
        })
        .catch(() => {
            document.querySelector('.location').textContent = 'Error';
            document.querySelector('.temperature').innerHTML = '--<sup>°C</sup>';
            document.querySelector('.weather').textContent = '--';
            document.querySelector('.humidity').textContent = 'Humidity: --%';
            document.querySelector('.datetime').textContent = '--';
            document.querySelector('.day-night').textContent = '❓';
        });
});

Step 4: Fetch Weather Data with PHP (weather.php)

In the weather.php file, we will write the PHP code to fetch weather data from the Open-Meteo API based on the user’s location. We will use the user’s IP address to determine their location and then make a request to the Open-Meteo API to retrieve the current weather data. Finally, we will return this data as JSON to be consumed by our JavaScript code in script.js.

  • Auto-detect user location using IP address
  • Fetch weather data from Open-Meteo API based on detected location
  • Return weather data as JSON for frontend consumption
<?php 
// Auto-detect IP address
$ip $_SERVER['REMOTE_ADDR'];

// Get location info from ip-api.com (free, no API key required)
$geo_url "http://ip-api.com/json/{$ip}?fields=status,message,country,regionName,city,lat,lon";
$geo_response = @file_get_contents($geo_url);
$geo_data $geo_response json_decode($geo_responsetrue) : null;

if (
$geo_data && $geo_data['status'] === 'success') {
    
$lat $geo_data['lat'];
    
$lon $geo_data['lon'];
    
$location $geo_data['city'] . ', ' $geo_data['country'];
} else {
    
// Fallback to New York if geolocation fails
    
$lat 40.7128;
    
$lon = -74.0060;
    
$location 'New York, USA';
}


// Open-Meteo API (no API key required)
$weather_url "https://api.open-meteo.com/v1/forecast?latitude={$lat}&longitude={$lon}&current_weather=true&hourly=relative_humidity_2m,weathercode";
$weather_response = @file_get_contents($weather_url);
$weather_data $weather_response json_decode($weather_responsetrue) : null;

if (
$weather_data && isset($weather_data['current_weather'])) {
    
$temperature $weather_data['current_weather']['temperature'];
    
$is_day $weather_data['current_weather']['is_day'] == 1;
    
$datetime date('l, H:i'strtotime($weather_data['current_weather']['time']));
    
    
// Get humidity from hourly data (nearest hour)
    
$humidity '--';
    if (isset(
$weather_data['hourly']['time']) && isset($weather_data['hourly']['relative_humidity_2m'])) {
        
$now $weather_data['current_weather']['time'];
        
$idx array_search($now$weather_data['hourly']['time']);
        if (
$idx !== false) {
            
$humidity $weather_data['hourly']['relative_humidity_2m'][$idx];
        }
    }

    
// Weather description from weathercode
    
$weather_codes = [
        
=> 'Clear sky',
        
=> 'Mainly clear',
        
=> 'Partly cloudy',
        
=> 'Overcast',
        
45 => 'Fog',
        
48 => 'Depositing rime fog',
        
51 => 'Light drizzle',
        
53 => 'Drizzle',
        
55 => 'Dense drizzle',
        
56 => 'Freezing drizzle',
        
57 => 'Dense freezing drizzle',
        
61 => 'Slight rain',
        
63 => 'Rain',
        
65 => 'Heavy rain',
        
66 => 'Freezing rain',
        
67 => 'Heavy freezing rain',
        
71 => 'Slight snow fall',
        
73 => 'Snow fall',
        
75 => 'Heavy snow fall',
        
77 => 'Snow grains',
        
80 => 'Slight rain showers',
        
81 => 'Rain showers',
        
82 => 'Violent rain showers',
        
85 => 'Slight snow showers',
        
86 => 'Heavy snow showers',
        
95 => 'Thunderstorm',
        
96 => 'Thunderstorm with hail',
        
99 => 'Thunderstorm with heavy hail',
    ];
    
$weathercode $weather_data['current_weather']['weathercode'];
    
$weather $weather_codes[$weathercode] ?? 'Unknown';
} else {
    
$temperature '--';
    
$weather 'Unavailable';
    
$humidity '--';
    
$is_day true;
    
$datetime date('l, H:i');
}

// Return data as JSON
header('Content-Type: application/json');
echo 
json_encode([
    
'location' => $location,
    
'temperature' => $temperature,
    
'weather' => $weather,
    
'humidity' => $humidity,
    
'is_day' => $is_day,
    
'datetime' => $datetime
]);
?>

🎯 Final Output

Once you have completed the above steps, your temperature widget should be fully functional and display real-time weather information based on the user’s location. The widget will show the current temperature, weather description, humidity, date & time, and a day/night indicator icon.

  • 🌡️ Current temperature (°C)
  • 📍 Auto-detected city & country
  • 🌤 Weather condition
  • 💧 Humidity
  • 🕒 Date & time
  • 🌞/🌜 Day or Night indicator

All fully dynamic and automatic.

📌 Use Cases of Weather Widget

  • Personal Blogs: Display local weather conditions to enhance user engagement.
  • Travel Websites: Show current weather at popular destinations to help travelers plan their trips.
  • News Portals: Provide real-time weather updates alongside news articles.
  • Event Pages: Inform attendees about the weather forecast for outdoor events.

🚀 Conclusion

In this tutorial, we have successfully created a real-time temperature widget using JavaScript and PHP. This widget automatically detects the user’s location, fetches live weather data from the Open-Meteo API, and displays it in a visually appealing format. You can easily customize the design and functionality of the widget to suit your website’s needs. This is a great way to enhance user experience by providing relevant and timely information. Happy coding!

Looking for expert assistance to implement or extend this script’s functionality? Submit a Service Request

Leave a reply

construction Need this implemented in your project? Request Implementation Help → keyboard_double_arrow_up