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).
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>
Sunset time will be displayed here.