AJAX xmlhttprequest keeps staying at readyState 1

Hi, would be great if you had an idea what is happening here - it works in an other test environment, but as soon as I want to use it in my Kirby project, the readyState keeps being 1 and it does not enter the ourRequest.open () function:

var btn = document.getElementById("send_btn");

btn.addEventListener("click", function() {

    var ourRequest = new XMLHttpRequest();

    ourRequest.open('GET', 'https://learnwebcode.github.io/json-example/animals-1.json');

    console.log(ourRequest.readyState);

    ourRequest.onload = function() {

      alert(ourRequest.readyState);

      if (ourRequest.status >= 200 && ourRequest.status < 400) {

        var ourData = JSON.parse(ourRequest.responseText);

        console.log(ourData);

      } else {

        console.log("We connected to the server, but it returned an error.");

      }

      

    };

  

    ourRequest.onerror = function() {

      console.log("Connection error");

    };

  

  });

Don’t you have to send the request: ourRequest.send();?

Yes i think you need .send() too. I did the following in a Kirby template and it works fine…

<script>
  function reqListener() {
    var data = JSON.parse(this.responseText);
    alert(this.readyState);
    if (this.status >= 200 && this.status < 400) {
      console.log(data);
    } else {
      console.log("We connected to the server, but it returned an error.");
    }
  }

  function reqError(err) {
    console.log('Fetch Error :-S', err);
  }

  var oReq = new XMLHttpRequest();
  oReq.onload = reqListener;
  oReq.onerror = reqError;
  oReq.open('get', 'https://learnwebcode.github.io/json-example/animals-1.json', true);
  oReq.send();
</script>

Many thanks for your reponse! I changed it to the fetch API and nox it works perfectly… :slight_smile:

Keep in mind that fetch doesnt work in older browsers.

https://caniuse.com/#feat=fetch