JavaScript AJAX Basics (retiring) Programming AJAX Parsing JSON Data

The structure and logic behind 4 steps of AJAX

Let's define what 4 steps of AJAX are for:

  1. Perfectly clear we assign AJAX object to the variable.
  2. We check that everything is fine with connection and AJAX status.
  3. 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?
  4. We send information from step 2 to the server. Please, help me clarify the issue. Many thanks!

2 Answers

Let 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"GET", "ajax_info.txt", true);
  //step 4. Send the request to the server resource you defined in step 3. 

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

Ok. Thanks! It clarifies a topic.