0
\$\begingroup\$

I frequently need to obtain some info about coordinates, because I have dynamic elements on a map (in Openlayers). So I use SetInterval and XMLHttpRequest Object to do it.

window.onload = function () {
    var requestURL = "data.geojson";
    var request = new XMLHttpRequest();
    request.onreadystatechange = function () {
        if (request.readyState == 4) {
            console.clear();
            console.log(request.response);
        }
    }
    var prueba = setInterval(function () {
        request.open('GET', requestURL, true);
        request.setRequestHeader('authenticated_user', 'terrain');
        request.send();
    }, 2000);
}

Is It the correct way?

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

First of all, readyState 4 simply means XHR is done. The response, however, can still either be a success (2xx) or a failure (4xx, 5xx). In order to distinguish a success from an error, you should also check status.

Next would be the reuse of the XHR instance. Although it's perfectly valid (open reinitializes the instance), you'll have to be absolutely sure subsequent calls aren't affected by the previous calls. It's probably much safer to just create a new instance of XHR for each request.

Then instead of window.onload, consider using addEventListener. The issue is that there might be other scripts assigning a callback to window.onload, overwriting your handler. On the other hand, multiple calls to addEventListener will just append handlers.

A simpler way to do it, assuming your target audience doesn't use legacy browsers, is fetch. It's essentially jQuery's $.ajax but natively implemented.

window.addEventListener('load', event => {
  setInterval(() => {
    fetch('data.geojson', {
      method: 'GET',
      headers: { authenticated_user: 'terrain' }
    }).then(() => {
      console.clear();
      console.log(request.response);
    })
  }, 2000)
})
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.