0

I am new to AJAX, As i understood that the handler function executes when response is ready.

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

And then we create and send our request

xhttp.open("GET", url, true);
xhttp.send();

does it make sense to handle the response while not sending the request yet !? Thanks

  • Possible duplicate of [AJAX onreadystatechange executing before post state change?](https://stackoverflow.com/questions/26965435/ajax-onreadystatechange-executing-before-post-state-change) – Mihai Alexandru-Ionut Oct 01 '17 at 10:44
  • 2
    You're not handling the response before sending the request. You're defining a function that will be called _when_ the response is returned. Big difference. – Andy Oct 01 '17 at 10:45
  • 3
    Welcome to the asynchronous nature of javascript, everything is done in bite size pieces. What's happening is that we first set up the code to handle the response, and then we send the response. The handler fires when the ajax request returns data. – Mikkel Oct 01 '17 at 10:46

1 Answers1

0

It makes sense because we may get the response while the response event handler was not set. Also, we do not handle the response right away, but we define the handler function which deals with the response.

On the other hand, in 99% of cases one will make no mistake to define the handler after the send(), in case he does not care whether the request failed immediately.

So, if there is no other way, than define the response handler after sending the request, but in all other cases do it a proper and secure way - before.

skobaljic
  • 9,379
  • 1
  • 25
  • 51