AJAX - The XMLHttpRequest Object


The core element of AJAX is the XMLHttpRequest object.

  1. Make an XMLHttpRequest object
  2. Create a callback function.
  3. Open the XMLHttpRequest thing
  4. Submit a Request to a Server

The XMLHttpRequest Object

Most new web browsers can handle the XMLHttpRequest tool.

The XMLHttpRequest lets you swap information with a web server without users noticing. This allows you to refresh sections of a webpage without reloading the entire page.


Create an XMLHttpRequest Object

Most web browsers like Chrome, Firefox, Internet Explorer (IE), Edge, Safari, and Opera come with a built-in feature called the XMLHttpRequest object.

To make a new XMLHttpRequest object, you use this syntax:

variable = new XMLHttpRequest();

Define a Callback Function

A callback function is a function that you pass as a parameter to another function.

In this situation, the callback function needs to have the code that runs when the response is prepared.

xhttp.onload = function() {
  // What to do when the response is ready
}

Send a Request

To ask a server for something, you can utilize the open() and send() actions of theXMLHttpRequestobject:

xhttp.open("GET", "ajax_info.txt");
xhttp.send();

Access Across Domains

Modern web browsers prevent accessing data from different websites for security reasons.

It's necessary for the webpage and the XML file it's attempting to load to be on the same server.

The samples on W3Schools website only display XML files from W3Schools website.

If you plan to put the example provided onto your website, the XML files you use must be stored on your own server.


XMLHttpRequest Object Methods

Method Description
new XMLHttpRequest() Produces a fresh XMLHttpRequest object.
abort() Stops the ongoing request.
getAllResponseHeaders() Provides details about the header.
getResponseHeader() Provides detailed details about the header.
open(method, url, async, user, psw) Describes the request with the following details:

method: Indicates the type of request, either GET or POST.
url: Specifies the location of the file.
async: Can be set to true for asynchronous or false for synchronous.
user: Optional field for providing a username.
psw: Optional field for providing a password.
send() Transmits a request to the server
Applied for GET requests
send(string) Transmits the message to the server.
Applies to POST requests.
setRequestHeader() Inserts a set of information in the header to be dispatched.

XMLHttpRequest Object Properties

Property Description
onload Creates a function that gets executed when a request is received (loaded).
onreadystatechange Creates a function that gets executed when the readyState property changes.
readyState Indicates the state of the XMLHttpRequest:
0: Request not started
1: Server connection established
2: Request received
3: Processing request
4: Request completed, and response is available
responseText Returns the data from the response as a string.
responseXML Provides the output information in XML format.
status Returns the status code of a request:
200: "OK"
403: "Forbidden"
404: "Not Found"
For a detailed list, visit the Http Messages Reference.
statusText Returns the message about the status (for example, "OK" or "Not Found").

The onload Property

Using the XMLHttpRequest object, you can set up a callback function that runs once the request gets a response.

The task is to define the function within the onload property of the XMLHttpRequest object:


Multiple Callback Functions

If you need to do several things with AJAX on a website, it's best to make a single function to handle the XMLHttpRequest object and a separate function for each task's response.

The function needs the website address (URL) and which function to execute when the website responds.

Example

loadDoc("url-1", myFunction1);

loadDoc("url-2", myFunction2);

function loadDoc(url, cFunction) {
  const xhttp = new XMLHttpRequest();
  xhttp.onload = function() {cFunction(this);}
  xhttp.open("GET", url);
  xhttp.send();
}

function myFunction1(xhttp) {
  // action goes here
}
function myFunction2(xhttp) {
  // action goes here
}

The onreadystatechange Property

The readyState attribute shows the condition of the XMLHttpRequest.

The onreadystatechange property specifies a callback function that runs when there is a change in the readyState.

The status and statusText properties store information about the status of the XMLHttpRequest object.

Property Description
onreadystatechange Creates a function to execute when the readyState property alters.
readyState The XMLHttpRequest status is described below:
0: Request not started
1: Server connection established
2: Request received
3: Processing request
4: Request completed and response is available
status 200 means "OK", 403 means "Forbidden", and 404 means "Page not found". For more details, visit the Http Messages Reference page.
statusText Returns the message that tells if something is "OK" or "Not Found".

The onreadystatechange function gets triggered whenever the readyState changes.

When thereadyState reaches 4 and the 'status' is 200, it means the response is ready.

The onreadystatechange event occurs four times (1-4), once for each change in the readyState.