0

I am retrieving data from database to display it in label.

let work_type = "cooking";

let xmlhttp =  createXMLHttp();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        document.getElementById("work_cost").innerHTML = this.responseText;
    }
};
xmlhttp.open("GET", "../php/functions.php?type=" + work_type , true);
xmlhttp.send();


console.log(document.getElementById("work_cost").innerHTML);

The problem is that console.log displays previous data even though label "work_cost" changes perfectly. How can I get real label value that I see?

For example: 1. I get "2" from server. 2. Place "2" in my label 3. console.log (label.value) displays "undefined". 4. Dropdown menu changes 5. I go to server again, get "3" now 6. Place "3" in label. 7. Try to console.log(label.value). I expect to see "3" because thats what I see in my webpage but console says "2"

So it seems like console sees one step previous only.

vytaute
  • 1,260
  • 4
  • 16
  • 36

1 Answers1

1

The console.log statement is being executed immediately after you define the HTTP request, but before the response has been returned from the server.

Remember that the server response takes time.

You can think of it like this set of instructions:

  1. Create an HTTP request object
  2. For this request, when we get a response later, run the following code:
    • set the button label to the contents of the response
  3. Send the request off to the server
  4. Log the current contents of the label

Note that 4 doesn't wait for the response to come back. Sending the response is non-blocking. The response will be processed some time later.

Sometimes when you're developing locally, it helps to throttle your network in devtools so you can exaggerate the delay between request and response. In Chrome you can do this by opening the developer tools and selecting the network tab, then locating this dropdown:

Chrome devtools network throttle location

Ed_
  • 18,798
  • 8
  • 45
  • 71