⇧
vadnica-logo
My Services About the Project Telegram O meni O meni

The XMLHttpRequest Object

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.

EXAMPLE
RESULT

The Entire Process Takes Place in Four Steps:

  1. We create a new instance of the XMLHttpRequest object.
  2. We define a callback function that will handle the response.
  3. We prepare the request (specify the method and the file URL).
  4. We send the request to the web server.

Creating and Setting Up the 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.