Mahmoud Mahmoud - 3 years ago 163
Ajax Question

Why we handle the response before the request in AJAX?

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download