javascripthtmlxmlhttprequest

Read variable from a file via javascript in an html file (client side)


I'm having an html file location.html and a file with data location.data both on the same webserver in the same directory. the contens of location.data is always the current location data in the form

{"lat":"44.17027","lon":"15.595542","timestamp":"1723663819127","hdop":"2.394","altitude":"510.35","speed":"0.73396146"}

it is written via json_encode() in another php file. Now I need to read this data in a javascript in location.html into an array to display it on a map via leaflet. (It has to be html)

I just can't manage to get this done. I tried XMLHttpRequest() with no success. Would appreciate any other (elegant) method.

<script>
var locx = new XMLHttpRequest();

locx.open('GET', 'location.data');

locx.onreadystatechange = function () {
   if (locx.readyState === 4 && locx.status === 200) {
       var locationData = locx.responseText;
   }
};

locx.send();
</script>

Solution

  • If the fetch works (and it should), then the rest will look like this

    Working example using PHP to generate JSON

    https://plungjan.name/SO/leafletjson

    const showMap = data => {
      const { lat, lon } = data;
    
      // Initialize the map
      const map = L.map('map').setView([lat, lon], 13); // 13 is zoom level
    
      // Add OpenStreetMap tile layer
      L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        maxZoom: 19,
        attribution: '&copy; OpenStreetMap contributors'
      }).addTo(map);
    
      // Add a marker to the map at the fetched coordinates
      L.marker([lat, lon]).addTo(map)
        .bindPopup(`Location: [${lat}, ${lon}]`)
        .openPopup();
    };
    
    showMap(data); // remove this line on your server and uncomment the fetch
    /* 
    fetch('location.data') // or fetch('jsonGeneratingPHP.php')
      .then(response => {
        if (!response.ok) { // added more fine grained error handling
          throw new Error(`Network response was not ok (status: ${response.status})`);
        }
        return response.json(); // Parse the JSON only if the response is ok
      })
     .then(showMap)
      .catch(error => console.error('Error fetching the location data:', error));
    */  
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" />
    <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
    <div id="map" style="height: 400px;"></div>
    
    
    
    <script>
    // delete this script on your server and uncomment the commented fetch 
    // test data, remove when fetch works
    const data = { "lat": "44.17027", "lon": "15.595542", "timestamp": "1723663819127", "hdop": "2.394", "altitude": "510.35", "speed": "0.73396146" };
    </script>