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.
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.
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.
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.
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?