Skip to main content

XMLHttpRequest Object

 The keystone of AJAX is the XMLHttpRequest object.

The XMLHttpRequest Object

All modern browsers support the XMLHttpRequest object.

The XMLHttpRequest object can be used to exchange data with a server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.


Create an XMLHttpRequest Object

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

Syntax for creating an XMLHttpRequest object:

variable new XMLHttpRequest();

<!DOCTYPE html>
<html>
<body>

<h1>The XMLHttpRequest Object</h1>

<p id="demo">Let AJAX change this text.</p>

<button type="button" onclick="loadDoc()">Change Content</button>

<script>
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "ajax_info.txt", true);
  xhttp.send();
}
</script>

</body>
</html>


output

The XMLHttpRequest Object

Let AJAX change this text.

------------------------------------------------

The "ajax_info.txt" file used in the example above, is a simple text file and looks like this:


<h1>AJAX</h1>
<p>AJAX is not a programming language.</p>
<p>AJAX is a technique for accessing web servers from a web page.</p>
<p>AJAX stands for Asynchronous JavaScript And XML.</p>


XMLHttpRequest Object Methods

MethodDescription
new XMLHttpRequest()Creates a new XMLHttpRequest object
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)
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

XMLHttpRequest Object Properties

PropertyDescription
onreadystatechangeDefines a function to be called when the readyState property changes
readyStateHolds 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
responseTextReturns the response data as a string
responseXMLReturns the response data as XML data
statusReturns the status-number of a request
200: "OK"
403: "Forbidden"
404: "Not Found"
For a complete list go to the Http Messages Reference
statusTextReturns the status-text (e.g. "OK" or "Not Found")



Comments