AJAX XMLHttpRequest

AJAX XMLHttpRequest Object

The keystone of all traditional AJAX applications is the XMLHttpRequest object.

All modern browsers strictly support the XMLHttpRequest object out of the box.


Creating the Object

To communicate with a server, you must first create a new instance of this object.

You simply assign the new XMLHttpRequest() constructor to a variable.

Once created, this variable holds the power to send requests and catch server responses!


The onload Property

Sending a request across the internet takes an unpredictable amount of time.

Because of this, you must define a callback function that runs only when the request finishes.

You define this function using the onload property of your XMLHttpRequest object.

XMLHttpRequest Setup Example:

// 1. Create the object
const xhttp = new XMLHttpRequest();

// 2. Define the callback function xhttp.onload = function() { // The 'this' keyword refers to the xhttp object itself console.log("Server replied: " + this.responseText); }

// 3. Send the request xhttp.open("GET", "https://jsonplaceholder.typicode.com/users/1"); xhttp.send();


SEO and Asynchronous Code

Running HTTP requests asynchronously ensures the browser never freezes while waiting for data.

A perfectly smooth, non-blocking user interface is highly favored by modern search engine algorithms.

Always define your onload function before you execute the send() command to avoid race conditions!


Exercise 1 of 1

?

Which property of the XMLHttpRequest object is used to define the function that executes when the server response arrives?