Current Location: Home> Latest Articles> How to Use AJAX + PHP to Retrieve the Sunset Time of Your Location in Real-Time

How to Use AJAX + PHP to Retrieve the Sunset Time of Your Location in Real-Time

M66 2025-06-12

In modern web development, AJAX allows web pages to interact with servers without refreshing, enhancing the user experience. Today, we'll combine AJAX and PHP to create a feature that retrieves the sunset time of a location in real-time based on the user's geographical coordinates (latitude and longitude).

Step 1: Get the User's Location

First, we need to obtain the user's geographical location. HTML5 provides a navigator.geolocation interface that can be used to get the user's current latitude and longitude. This interface requests the user's location information through the browser. Here's the code:

<!DOCTYPE html>  
<html lang="en">  
<head>  
    <meta charset="UTF-8">  
    <meta name="viewport" content="width=device-width, initial-scale=1.0">  
    <title>Real-time Sunset Time</title>  
    <script>  
        function getLocation() {  
            if (navigator.geolocation) {  
                navigator.geolocation.getCurrentPosition(showPosition);  
            } else {  
                alert("This browser does not support geolocation.");  
            }  
        }  
        var latitude = position.coords.latitude;  
        var longitude = position.coords.longitude;  

        // Call the PHP API to get the sunset time  
        fetchSunsetTime(latitude, longitude);  
    }  

    function fetchSunsetTime(latitude, longitude) {  
        var xhr = new XMLHttpRequest();  
        xhr.open("GET", "https://m66.net/sunset-time.php?lat=" + latitude + "&lon=" + longitude, true);  
        xhr.onreadystatechange = function() {  
            if (xhr.readyState == 4 && xhr.status == 200) {  
                var response = JSON.parse(xhr.responseText);  
                document.getElementById("sunset-time").innerHTML = "Sunset Time: " + response.sunset;  
            }  
        };  
        xhr.send();  
    }  
</script>  



Real-time Sunset Time



Sunset time will be displayed here.




In the above code, when the user clicks the "Get Sunset Time for My Location" button, the browser requests the user's geographical location. Once the latitude and longitude are obtained, we use an AJAX request to call the PHP backend API to fetch the sunset time for that location.

Step 2: PHP Backend API

To calculate the sunset time based on the user's location, we need to use an external API to get the sunset information. Here, we use a public API that allows you to query the sunset time for a location using latitude and longitude. Below is the PHP code that handles the AJAX request and retrieves the sunset time.

<?php  
// sunset-time.php  
<p>// Get the latitude and longitude passed by the user<br>
$latitude = isset($_GET['lat']) ? floatval($_GET['lat']) : 0;<br>
$longitude = isset($_GET['lon']) ? floatval($_GET['lon']) : 0;</p>
<p>// Check if the latitude and longitude are valid<br>
if ($latitude == 0 || $longitude == 0) {<br>
echo json_encode(['error' => 'Invalid latitude or longitude']);<br>
exit;<br>
}</p>
<p>// Use the free Sunset API to get the sunset time<br>
$url = "<a rel="noopener" target="_new" class="cursor-pointer">https://api.sunsetapi.net/json?lat={$latitude}&lng={$longitude}</a>";<br>
$response = file_get_contents($url);<br>
if ($response === FALSE) {<br>
echo json_encode(['error' => 'Unable to retrieve sunset time']);<br>
exit;<br>
}</p>
<p>// Parse the API response data<br>
$data = json_decode($response, true);</p>
<p>// Ensure the sunset time is available in the response<br>
if (isset($data['results']['sunset'])) {<br>
$sunset = $data['results']['sunset'];<br>
echo json_encode(['sunset' => $sunset]);<br>
} else {<br>
echo json_encode(['error' => 'Sunset time not found']);<br>
}<br>
?><br>

In this PHP script, we receive the latitude and longitude parameters (lat and lon) via a GET request from the client, then call the external API to retrieve the sunset time for that location. After retrieving the data, we return it to the client in JSON format.

Step 3: Start the Server and Test

  1. Save the above HTML and PHP code as index.html and sunset-time.php, respectively.

  2. Ensure your PHP environment is working correctly (e.g., using XAMPP or WAMP server, etc.).

  3. Place the files in the root directory of your server and start the server.

  4. Access the index.html page and click the button. The sunset time for your location should be displayed on the page.

Results Display

When the user clicks the button to get the sunset time, the AJAX request sends the latitude and longitude to the backend PHP. The backend uses the external API to retrieve the sunset time and returns it to the client. The client then updates the page content using JavaScript, displaying the sunset time.