Why does new XMLHttpRequest already contain a response?

Why does new XMLHttpRequest already contain a response?
0.0 0

#1

I am trying to understand how code executes in an XMLHttp request. In the following example, I print to console the XHMLHttp request twice, once before I ‘open’ and ‘send’ it, and then again once it is ‘DONE.’

I do not understand why my first console.log request already contains a response from the API - for example, the “response” and “responseText” fields already contain the Free Code Camp data I am requesting. Shouldn’t those fields be blank? At the first console.log line in my code, I have yet to specify the URL of the server I want to contact and I have yet to open or send the request. Why are they already filled when I print to the console the first time?

var topHundredURL = "https://fcctop100.herokuapp.com/api/fccusers/top/recent";
var xhr = new XMLHttpRequest();
console.log(xhr);
xhr.open('GET',topHundredURL);
xhr.send();
xhr.onreadystatechange = function(){
  if(xhr.readyState == XMLHttpRequest.DONE){
    console.log(xhr);
  }
}

Thanks so much for your help!!!


#2

Chrome (and I assume FF) evaluates values at the moment you click to expand (notice the blue i? hover over it in the console):

evaluate

You can wrap stuff after the first console log in setTimer with some delay, so you can manage to click the first log:

var topHundredURL = 'https://fcctop100.herokuapp.com/api/fccusers/top/recent';
var xhr = new XMLHttpRequest();
console.log(xhr);

setTimeout(() => {
  xhr.open('GET', topHundredURL);
  xhr.send();
  xhr.onreadystatechange = function() {
    if (xhr.readyState == XMLHttpRequest.DONE) {
      console.log(xhr);
    }
  };
}, 5000);


#3

Thanks for the explanation!!
Thanks @jenovs!