The foundation of all AJAX communication is the XMLHttpRequest object. This object enables data
exchange with a server in the background, which means we can update parts of a page without reloading the entire
document.
XMLHttpRequest object.The syntax for creating a new object is simple. This line of code is typically written at the beginning of our AJAX function:
const xhttp = new XMLHttpRequest();
The onload property defines the function to be executed only when the browser receives the complete
response from the server. This is the most modern way to monitor a successful transfer:
xhttp.onload = function() {
// Code that handles the response (e.g., printing to the page)
}
For actual communication, we use the open() (preparation) and send() (submission)
methods. You can read more about their parameters in the links below:
xhttp.open("GET", "data.json");
xhttp.send();
Security Note (CORS): For security reasons, modern web browsers do not allow cross-domain access. This means that both the web page and the file you are requesting must reside on the same server.
Asynchronous Operation: The open() method takes true as its third
parameter by default. This ensures that the JavaScript code does not freeze while waiting for the server response,
allowing the user to continue interacting with the page seamlessly.