JavaScript AJAX XMLHttp
JavaScript Basics

JavaScript AJAX XMLHttp

AJAX and the XMLHttpRequest Object

The XMLHttpRequest object is the foundation of AJAX, enabling asynchronous communication with a web server without reloading the entire page.

Steps to Use XMLHttpRequest

  1. Create an XMLHttpRequest object
  2. Define a callback function
  3. Open the XMLHttpRequest object
  4. Send a request to the server

Creating an XMLHttpRequest Object

All modern browsers (Chrome, Firefox, IE, Edge, Safari, Opera) have a built-in XMLHttpRequest object.

Syntax:

let xhr = new XMLHttpRequest();

Defining a Callback Function

A callback function is a function passed as a parameter to another function. It executes when the response from the server is ready.

xhr.onload = function() {  // Code to execute when the response is ready}

Sending a Request

Use the open() and send() methods to send a request to the server.

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

Complete Example

// Create an XMLHttpRequest object
let xhr = new XMLHttpRequest();

// Define a callback function
xhr.onload = function() {
  // Code to handle the response
  document.getElementById("demo").innerHTML = this.responseText;
}

// Send a request
xhr.open("GET", "ajax_info.txt");
xhr.send();

Access Across Domains

For security reasons, modern browsers restrict access across different domains. This means both the web page and the requested resource must be on the same server.

XMLHttpRequest Object Methods

Method

Description

new XMLHttpRequest()

Creates a new XMLHttpRequest object

abort()

Cancels the current request

getAllResponseHeaders()

Returns all header information

getResponseHeader()

Returns specific header information

open(method, url, async, user, psw)

Specifies the request

send()

Sends the request (used for GET requests)

send(string)

Sends the request (used for POST requests)

setRequestHeader()

Adds a label/value pair to the header to be sent

XMLHttpRequest Object Properties

Property

Description

onload

Defines a function to be called when the request is received

onreadystatechange

Defines a function to be called when the readyState changes

readyState

Holds the status of the XMLHttpRequest

responseText

Returns the response data as a string

responseXML

Returns the response data as XML

status

Returns the status number of a request

statusText

Returns the status text (e.g., "OK" or "Not Found")

The onload Property

The onload property allows you to define a callback function that executes when the request receives a response.

Example:

xhr.onload = function() {

  document.getElementById("demo").innerHTML = this.responseText;

}

xhr.open("GET", "ajax_info.txt");

xhr.send();

Multiple Callback Functions

For handling multiple AJAX tasks, create a function to execute the XMLHttpRequest object and separate callback functions for each task.

Example:

function loadDoc(url, callbackFunction) {
  let xhr = new XMLHttpRequest();
  xhr.onload = function() {
    callbackFunction(this);
  }
  xhr.open("GET", url);
  xhr.send();
}

function myFunction1(xhr) {
  // Code for the first callback
}

function myFunction2(xhr) {
  // Code for the second callback
}

// Usage
loadDoc("url-1", myFunction1);
loadDoc("url-2", myFunction2);

The onreadystatechange Property

The readyState property indicates the status of the XMLHttpRequest.

  • 0: Request not initialized
  • 1: Server connection established
  • 2: Request received
  • 3: Processing request
  • 4: Request finished and response is ready

The onreadystatechange property defines a callback function that executes whenever the readyState changes.

Example:

function loadDoc() {  let xhr = new XMLHttpRequest();  xhr.onreadystatechange = function() {    if (this.readyState == 4 && this.status == 200) {      document.getElementById("demo").innerHTML = this.responseText;    }  };  xhr.open("GET", "ajax_info.txt");  xhr.send();}

The onreadystatechange event is triggered multiple times (1-4), once for each change in the readyState. When readyState is 4 and status is 200, the response is ready.

Take a look into your desired course