XML DOM XMLHttpRequest Object

Through the XMLHttpRequest object, you can update part of the web page without reloading the entire page.

XMLHttpRequest object

The XMLHttpRequest object is used to exchange data with the server in the background.

The XMLHttpRequest object is a dream for developers because you can:

  • Update the web page without reloading the page
  • Request data from the server after the page is loaded
  • Receive data from the server after the page is loaded
  • Send data to the server in the background

Methods of the XMLHttpRequest object

Method Description
abort() Cancel the current request.
getAllResponseHeaders() Return the header information.
getResponseHeader() Return the value of the specified HTTP response header.
open(method,url,async,uname,pswd)

Specify the type of request, URL, whether the request should be processed asynchronously, and other optional properties of the request.

  • method: Request type: GET or POST
  • url: The location of the file on the server
  • async: true (asynchronous) or false (synchronous)
send(string)

Send the request to the server.

stringNote: This is only used for POST requests

setRequestHeader() Add a label/value pair to the headers to be sent.

Attributes of the XMLHttpRequest object

Attribute Description
onreadystatechange Store the function (or function name) that is automatically called each time the readyState attribute changes.
readyState

Save the state of XMLHttpRequest. The change from 0 to 4:

  • 0: The request has not been initialized
  • 1: The server connection has been established
  • 2: The request has been received
  • 3: The request is being processed
  • 4: The request has been completed, and the response is ready
responseText Return response data as a string.
responseXML Return response data in XML format.
status Return status code (e.g., "404" for "Not Found", or "200" for "OK").
statusText Return status text (e.g., "Not Found" or "OK").