Knowledge of XMLHttpRequest

XMLHttpRequest helps browser in transferring data between a browser and server. Without refreshing a full page, it provides a simple technique to fetch data from a server. The best part of XMLHttpRequest is that updates a part of the web page without interrupting what the user is performing.

How to use XMLHttpRequest

Following are the steps that you must follow to build AJAX applications using XMLHttpRequest-

  1. Create an object of XMLHttpRequest by calling its constructor.
  2. Assign a function to an event handler onreadystatechange. In the function check the value of readyState and status to obtain the response from the server.
  3. Call open() method to initialize a method. In this method, specify three parameters- the type of HTTP method, URL to whom the request is to be sent, and true to call asynchronously.
  4. Call send() method to send the request to the server.
var request = new XMLHttpRequest();
request.onreadystatechange = function(){
   if(this.readyState == 4 && this.status == 200){
      var response = this.responseText;
};"GET", "url", true);

Properties of XMLHttpRequest

Properties Explanation
onreadystatechange Use to specify the function name that will be invoked whenever the value of readyState changes.
readyState It contains the status of XMLHttpRequest object. The Range of this property is from 0 to 4.
0- request is not generated
1- connection with the server is made
2- the server receives request
3- request is processing
4- response is received, and request is finished
responseText It stores the response data in the form of string.
responseXML It stores the XML data received in response.
status Returns the status code(200 for OK, 403 for Forbidden, 404 for Not Found, and so on)
statusText It holds the text of the status.

Functions of XMLHttpRequest

Functions Explanation
abort() This function is used to cancel the current request.
getAllResponseHeaders() It returns all the response headers in the form of a string.
getResponseHeader() This function returns the value of the specified header.
open(method,url,async,uname,pswd) This method is used to initialized the request. It takes the following arguments -
method- the type of HTTP method such as GET, POST, etc.
url- Specifies the file on the server to send the request to.
async- It is optional, and by default it is true. A false value indicates that the request must be handled synchronously and true value indicates asynchronously.
username & password- Optional and by default it is null. Use for authentication purposes.
send(string) It sends the request to the server. If the HTTP method of a request is POST, then the argument of this function is not ignored.
setRequestHeader(header, value) This methods must be called before send() method and after open() method. It is used to set the header of HTTP request.