====== AJAX - Make an AJAX request using XMLHttpRequest ======
To fetch the content of a URI using an **XMLHttpRequest** object in JavaScript.
===== Background =====
**XMLHttpRequest** is the JavaScript class which underpins the concept of AJAX (Asynchronous JavaScript and XML). It allows a web page to load new data without reloading the page as a whole. This in turn allows many important types of web application to be coded entirely in JavaScript when it would previously have been necessary to rely on technologies such as Java applets or ActiveX.
Despite its name XMLHttpRequest is not limited to XML: it can be used to fetch any type of data, including other text-based formats such as JSON, and binary formats such as PNG or JPEG.
It is good practice to transfer data in structured form where possible, in order to cleanly separate the presentation layer (on the browser) from the business logic (on the server). Alternatively you can take the more direct approach of sending pre-formatted HTML or XHTML, which need only be parsed by the browser before being inserted into the document tree.
===== Scenario =====
Suppose you are developing a webmail application, and want the client to list the content of the user’s inbox. It can obtain the necessary raw data from the server by making a GET request to the URL /folders/inbox, accompanied by a pre-existing cookie which is used to identify and authenticate the user. The response to the GET request is an array of objects encoded as JSON.
===== Method =====
==== Overview ====
The method described here has six steps:
- Create a new XMLHttpRequest object.
- Specify what is to be fetched and how by calling open.
- Specify the expected responseType.
- Register an onreadystatechange event handler.
- Initiate the request by calling send.
- Wait for the event handler to be called.
- Create a new XMLHttpRequest object
The constructor should normally be called without any arguments:
var xhr = new XMLHttpRequest();
if (!xhr) {
alert('failed to create XMLHttpRequest object');
}
For subsequent requests you can choose between creating a new XMLHttpRequest object or reusing an old one (see below).
==== Specify what is to be fetched and how by calling open ====
The XMLHttpRequest constructor returns a request object which is in the UNSENT state. In order to progress to the OPENED state you must specify the URI to be fetched and HTTP method to be used. This is done by calling the open method:
xhr.open("GET", "/folders/inbox", true);
There are two required parameters and three optional ones:
- the HTTP request method (as a string),
- the URI to be fetched,
- the async flag (optional, normally true),
- the username (optional), and
- the password (optional).
- The HTTP request method tells the server what action to perform when it locates the resource identified by the URI. You will probably be familiar with the GET and POST methods that can be used within an HTML