JavaScript

Last Updated: 4/13/2023

AJAX

The XMLHttpRequest Object

  • All modern browsers support the XMLHttpRequest object.
  • The XMLHttpRequest object can be used to exchange data with a web server behind the scenes.

Example

const xhr = new XMLHttpRequest();
xhr.onload = function() {
    console.log(this);
}
xhr.open("GET", "/contents/countries.json");
xhr.send();

Methods

  • abort: Cancels the current request
  • getAllResponseHeaders: Returns header information
  • getResponseHeader: Returns specific header information
  • open(method, url, async, user, psw): Specifies the request
    • method: the request type GET or POST
    • url: the file location
    • async: true (asynchronous) or false (synchronous). default true
    • user: optional user name
    • psw: optional password
  • send: Sends the request to the server. Used for GET requests
  • send(string): Sends the request to the server. Used for POST requests
  • setRequestHeader: Adds a label/value pair to the header to be sent

Properties

  • readyState: Holds 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
  • responseText: Returns the response data as a string
  • responseXML: Returns the response data as XML data
  • status: Returns the status-number of a request
    • 200: "OK"
    • 403: "Forbidden"
    • 404: "Not Found"
  • statusText: Returns the status-text (e.g. "OK" or "Not Found")

Get Method

xhr.open("GET", "register?fname=ganesh&lname=kumar");
xhr.send();

Post Method using params

xhr.open("POST", "register");
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("fname=ganesh&lname=kumar");

Post Method using JSON

xhr.open("POST", "register");
xhr.setRequestHeader("Content-type", "application/json; charset=utf-8");
const data = {fname: "ganesh", lname: "kumar"};
xhr.send(JSON.stringify(data));

Reference