Ajax XMLHttpRequest

XMLHttpRequest (XHR): It is used for asynchronous communication between client and server and send HTTP or HTTPS requests to a web server and load the server response data back into the script.

It performs following operations:

  • Updates the webpage without reloading it.
  • Receive data from a server - after the page has loaded.
  • Send data to a server - in the background.

Create an XMLHttpRequest Object

var xmlHttpRqst = new XMLHttpRequest(); For All modern browsers (Chrome, Firefox, IE7+, Edge, Safari, Opera) 
var xmlHttpRqst = new ActiveXObject("Microsoft.XMLHTTP"); For IE5 and IE6

XMLHttpRequest Methods

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, password)

method: the request type GET or POST

url: the file location

async: true (asynchronous) or false (synchronous)

user: optional user name

password: optional password

send() Sends the GET request.
send(string) Sends the POST request.
setRequestHeader() It adds request headers.

Properties of XMLHttpRequest object are as follows:

onReadyStateChange It is called whenever readystate attribute changes. It must not be used with synchronous requests.
readyState

represents the state of the request. It ranges from 0 to 4.

0 : request not initialized

1 : server connection established

2 : request received

3 : processing request

4 : request finished and response is ready

reponseText returns response as text.
responseXML returns response as XML.
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")