JavaScript XMLHttpRequest Method, don't understand

Hi All,

I don’t really understand the below code.

const xhr = new XMLHttpRequest();
      xhr.open('POST', url, true);
      xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 201){
          const serverResponse = JSON.parse(xhr.response);
          console.log(serverResponse);
          document.getElementsByClassName('message')[0].textContent = serverResponse.userName + serverResponse.suffix;
        }
      };
      const body = JSON.stringify({ userName: userName, suffix: ' loves cats!' });
      xhr.send(body);

My question is why do we write the xhr.onreadystatechange function before we write the xhr.send().

Shouldn’t we send the body to the server first before waiting for a response and parsing the response?

I have read on stackoverflow that it is because ajax is asynchronous, means once the request is sent it will continue executing without waiting for the response.

However I still do not understand and can’t seem to see how the logic flows or how the code is executed.

Would appreciate if anyone can explain it to me clearer.

Thanks in advance =)

1 Like

The function that’s assigned to the onreadystatechange property of an XHR object isn’t executed right away but called when the readyState property of the same XHR object changes.

You write it beforehand because you don’t know when the readyState property will change, and if you write if after send(), the function may not execute in time.

Again, you don’t know when you’ll receive a response and there may not even be a response, so what you do is you make pre-arrangement about what to do with the response in case and as soon as a response is received.

Hi gaac510,

Thanks for your reply. Could I check with you if the readyState property changes when xhr.send() is executed?

Does this mean that it might throw an error if I were to execute xhr.send() prior to xhr.onreadystatechange as below?

const xhr = new XMLHttpRequest();
      xhr.open('POST', url, true);
      xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
      const body = JSON.stringify({ userName: userName, suffix: ' loves cats!' });
      xhr.send(body);
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 201){
          const serverResponse = JSON.parse(xhr.response);
          console.log(serverResponse);
          document.getElementsByClassName('message')[0].textContent = serverResponse.userName + serverResponse.suffix;
        }
      };
      

I did try the above code in the exercise and it seems to work just fine. So I’m not sure if writing the code as above is wrong and if it is I’m also not sure why since it seems to work.

Thanks for your time and reply.

Cheers!

This explains it well: XMLHttpRequest.readyState - Web APIs | MDN (mozilla.org)

1 Like

Hi gaac510,

One question on your reply. You mentioned that if we were to write the onreadystatechange function after send(), the function may not execute in time.

I don’t quite understand why it would not execute in time, since the body would have been sent and we are now waiting for a response?

Thanks much.

You live in a downtown apartment and one day you wanted to invite your bf/gf over to spend time together.

Your apartment was messy but you thought “I’ll clean it up while my bf/gf is on his/her way here”, and then you just texted your invitation.

Pretty much immediately you received a reply text from your bf/gf “I’m in downtown for some shopping right now, literally two minutes away from your apartment!”

Two minutes later, you bf/gf arrived and you didn’t cleanApartment() in time.

Moral of the story: Your bf/gf coming over was happening asynchronously to your plan of how events should occur, and you could have cleaned before you sent your invitation.

Hi gaac510,

If I understood your analogy correctly, you mean that it is possible that the response from send() is faster than the onreadystatechange function being called and it is not ready to receive the response?

Thanks for helping me understand. =)

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.