So I just finished writing my first Ajax function. I did it all from a google tutorial and w3schools and it's finally working. The only problem is I don't fully understand the logic of what is happening and am looking for an explanation!
Here is my full code
function loadPlayer(id)
{
var xmlhttp;
if (window.XMLHttpRequest)
xmlhttp=new XMLHttpRequest();
else if(window.ActiveXObject)
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
document.getElementById("newPlayer").innerHTML=xmlhttp.responseText;
};
xmlhttp.open("GET","http://localhost:8084/gmustudent/players?id=" + id,true);
xmlhttp.send();
}
My main question is about the order that I wrote this code as it pertains to each statement. I am confused because within the onreadystatechange function I am grabbing the response text and putting it in the newPlayer div. However, it is not until after this statement that I actual get the data from the url asynchronously.
So I'm confused because I do not understand how you can put the response text in the div, if you haven't gotten it yet. I see that it works, I just don't understand why. So if anyone could explain what is going on here in simple terms I would really appreciate it. Especially as it pertains to the order that I am writing my statements and what each statement is actually doing. Thank you so much!