Ajax – Basics

AJAX stands for Asynchronous Javascript and XML

also knowns as …

XML HTTP Request (XHR)

The AJAX/XHR process consists of the following:

  1. Create an XML HTTP Request object
  2. Create a Callback function
  3. Open a Request
  4. Send the Request (to a webserver)
Creating an xml http request object

This is done by creating an object variable using the XMLHttpRequest() function:

var xhr = new XMLHttpRequest();

Creating a callback function

Create a function that will be called once ready state has changed to status 4:

xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
//action
}
};

OPen a request

Use the .open() function:. eg:

xhr.open('GET', 'sidebar.html');

Send the Request

Pass info to send (in the parenthesis) to the server:

xhr.send();


Ready State and Callbacks

Each stage of the process involves a readyState. Each step changes the ready stage of the request. A callback responds to the change in that state

An XML HTTP request object’s readyState property holds a number from 0 to 4. Zero to 3 represents stages from when the object is created to when the response is coming. ReadyState 4 is when the web server has sent everything it’s going to send.

Status Property

The object also returns a status as per the following

200 – 0k

401 – not authorised

404 – not found

500 – database  error

eg. To create a callback when the status is ok. The status has a property of .statusText to provide further info:

if (xhr.status === 200) {

//action

} else {
alert(xhr.statusText);
}

Displaying results

Use the XHR object’s responseText property:
xhr.responseText;