javascriptajaxxmlhttprequestonreadystatechange

Need Help Understanding Ajax Function


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!


Solution

  • this:

    xmlhttp.onreadystatechange=function() 
        {
            if (xmlhttp.readyState==4 && xmlhttp.status==200)
                document.getElementById("newPlayer").innerHTML=xmlhttp.responseText;
        };
    

    is an event handler which means that it gets executed when an event is fired. In this case its when the state changes of the request you made. The actual flow through the code is:

    1. You attach that event handler in the code above
    2. You make the actual request
    3. That event onreadystatechange gets fired repeatedly as the request is being processed (as the state changes)
    4. When the request is ready and is OK (that if block), it adds the response text to the div.

    So, you can see that you attach the event callback in #1, and then the code you care about finally gets executed later at #4.