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 trialAndrei Li
34,475 PointsThe structure and logic behind 4 steps of AJAX
Let's define what 4 steps of AJAX are for:
- Perfectly clear we assign AJAX object to the variable.
- We check that everything is fine with connection and AJAX status.
- We process received information. Or I am wrong? As far as understood this should be an information that server sends to the browser (client). So it might be a JSON, HTML or a link to the HTML. This line is responsible for proccessing information from the server.Am I wrong?
- We send information from step 2 to the server. Please, help me clarify the issue. Many thanks!
2 Answers
Alexander La Bianca
15,959 PointsLet me explain quickly with the following example:
function loadDoc() {
//step 1. as you clearly understand
var xhttp = new XMLHttpRequest();
//step 2. Here you are defining the function that should run once the data is 'ready'
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
//step 3. Define what type of request you are making (param 1) and where you are making that request to (param 2)
//you are also setting a boolean if the request should be asynchronous (param 3) . Note: that should always be true
xhttp.open("GET", "ajax_info.txt", true);
//step 4. Send the request to the server resource you defined in step 3.
xhttp.send();
}
Now this is the usual way to set up the request, but they don't run in that order since it is asynchronous hence 'AJAX' ;) The function you define in step 2 actually runs AFTER step 4 is executed.
In step 2, you can access the response from the server via accessing xhttp's context. In this exmaple -> this.responseText for exmaple
Andrei Li
34,475 PointsOk. Thanks! It clarifies a topic.