Just to clarify things:
The function ()
is triggered as onreadystatechange
when the request's state changes. (by the way: function()
is an anonymous function assigned to the onreadystatechange
eventListener)
The function linked to the onreadystatechange
eventListener is executed each time the XMLHttpRequest object's state changes.
Therefore, be mindful that this function is called repeatedly
you can verify this with an if
statement, like this
xhttp.onreadystatechange = function () {
// only for local file usage
if (xhttp.readyState === 4) {
// ...do something
}
}
to avoid unintended multiple executions.
(consider checking other readyState
values for loading screens and other purposes)
The true
or false
argument supplied to the open
function specifies whether the call should be asynchronous or not. If synchronous, the script will freeze until the server responds.
Here are the possible parameters according to MDN Documentation open:
void open(
DOMString method, // GET, POST, ...
DOMString url, // URL
optional boolean async, // if true, script continues executing
optional DOMString user, // Username, if required
optional DOMString password // Password, if needed
);
I suggest consulting the Documentation for functions, objects, etc., if you have doubts.
Here are some useful links on this particular topic (XMLHttpRequest):
MDN XMLHttpRequest
Below is a brief visualization of the "flow"
[enter loadDoc()] --call--> xhttp.open(..., true) --call--> xhttp.send(...) --> [exit loadDoc()]
[onEvent "readystatechange"] --> xhttp.onreadystatechange(...)