Skip to main content

JavaScript AJAX XMLHttpRequest

The XMLHttpRequest (XHR) object is a core component of AJAX and allows for asynchronous communication between a web page and a server.

It provides a way to send and receive data from a server without requiring a full page reload.

The XHR object is available in most modern web browsers and provides a flexible API for making HTTP requests.

Here are the basic steps involved in using the XHR object to make an AJAX request:

Create an instance of the XHR object​

var xhr = new XMLHttpRequest();

Open a connection to the server​

xhr.open("GET", "https://example.com/data.json", true);

The first parameter is the HTTP method to use (e.g. GET, POST, etc.), the second parameter is the URL to request, and the third parameter is a boolean indicating whether the request should be asynchronous.

Set any request headers​

xhr.setRequestHeader("Content-Type", "application/json");

You can set any custom request headers using the setRequestHeader() method.

Send the request​

xhr.send();

Handle the response​

xhr.onload = function () {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.log("Request failed. Returned status of " + xhr.status);
}
};

This sets up a callback function to handle the response when it is received.

In this example:

  • We check the status code of the response to determine if the request was successful or not, and then log the response text to the console.

XMLHttpRequest Object Methods​

The XMLHttpRequest object is used to make HTTP requests to a server and receive a response.

Here are the most commonly used methods:

  • open(method, url, async) - initializes a request. The parameters are: method - the HTTP method (e.g. "GET", "POST", "PUT", "DELETE", etc.). url - the URL to send the request to. async - whether the request should be asynchronous (true) or synchronous (false).

  • setRequestHeader(header, value) - sets a request header to be sent with the request. The parameters are: header - the name of the header. value - the value of the header.

  • send(data) - sends the request to the server. The parameter is: data - the data to send with the request, if any.

  • abort() - aborts the request.

  • getAllResponseHeaders() - returns all the response headers as a string.

  • getResponseHeader(header) - returns the value of a specific response header. The parameter is: header - the name of the header.

  • overrideMimeType(mimetype) - overrides the default MIME type returned by the server.

  • addEventListener(event, listener) - adds an event listener to the XMLHttpRequest object. The parameters are: event - the name of the event to listen for. listener - the function to be called when the event is fired.

  • removeEventListener(event, listener) - removes an event listener from the XMLHttpRequest object. The parameters are: event - the name of the event. listener - the function to be removed.

XMLHttpRequest Object Properties​

The XMLHttpRequest object has several properties that can be used to manage HTTP requests and responses.

Here are the most commonly used properties:

  • onreadystatechange - an event handler that is called whenever the readyState property changes.

  • readyState - the state of the request. Possible values are: 0 - UNSENT - the request has not been opened yet. 1 - OPENED - the request has been opened, but not yet sent. 2 - HEADERS_RECEIVED - the request headers have been received. 3 - LOADING - the response data is being received. 4 - DONE - the request is complete.

  • responseText - the response data as a string.

  • responseXML - the response data as an XML Document object.

  • status - the HTTP status code of the response.

  • statusText - the HTTP status message of the response.

  • timeout - the amount of time (in milliseconds) to wait for a response before aborting the request.

  • withCredentials - whether or not to include credentials (such as cookies) with the request.