Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

akash dikkaram
akash dikkaram
1,927 Points

Can SomeOne Explain The Code Flow In Order ?

Can SomeOne Explain The Code Flow In Order ?

    var a= new XMLHttpRequest();
    a.onreadystatechange=function()
    {
    if(a.readyState===4)
     {
        document.getElementById('ajax').innerHTML=a.responseText;
     }
     };
     a.open('GET','sidebar.html');
     function senda(){
      a.send();
      }

1 Answer

Farid Wilhelm Zimmermann
Farid Wilhelm Zimmermann
16,753 Points

Step 1: declare a new XHR object

var xhr = new XMLHttpRequest();

Step 2: setting a callback function

    //onreadystatechange is an event listener that gets trigered once the xhr(a) changes its state //

xhr.onreadystatechange = function() {

//if xhr state is equal to 4 (4 means it got its response back)//

if (xhr.readyState = 4) {

//updates div id=ajax with the xhr responseText//

document.getElementById('ajax').innerHTML=a.responseText;
 }
 };

Step 3: Open a Request

xhr.open('GET', 'sidebar.html");

Step 4: Send Request

xhr.send();

I used the variable xhr instead of a, but the context remains the same.

Further Explaination for .readyState property

īģŋ.readyState holds the status of the XMLHttpRequest:

0: request not initialized 1: server connection established 2: request received 3: processing request 4: request finished and response is ready

Happy Coding :)